如果文件名不包含换行符,则可以grep通过让grep打印匹配文件的名称并计算结果来避免多次调用。
local IFS=$'\n' # inside a function. Otherwise use some other way to save/restore IFS
matches=( $(grep -lw "$users" "$file1" "$file2") )
比赛次数是"${#matches[@]}"。
这里可能有一种使用方法grep --null -lw,但是我不确定如何解析输出。Bash var=( array elements )无法使用\0定界符代替\n。也许bash的mapfile内置功能可以做到吗?但可能不是,因为您使用指定了分隔符-d string。
可以count=$(grep -l | wc -l),但是您有两个外部进程,因此您最好grep分别在两个文件上运行。(相比于用fork + exec +动态链接器来启动一个单独的进程,启动开销grep与wc启动开销之间的差异很小)。
另外,与wc -l你没有发现哪个文件相匹配。
将结果捕获在数组中后,可能已经是您想要的结果,或者如果存在完全匹配的1个匹配项,则可以检查它是否是第一个输入。
local IFS=$'\n' # inside a function. Otherwise use some other way to save/restore IFS
matches=( $(grep -lw "$users" "$file1" "$file2") )
# print the matching filenames
[[ -n $matches ]] && printf 'match in %s\n' "${matches[@]}"
# figure out which input position the name came from, if there's exactly 1.
if [[ "${#matches[@]" -eq 1 ]]; then
if [[ $matches == "$file1" ]];then
echo "match in file1"
else
echo "match in file2"
fi
fi
$matches是${matches[0]}第一个数组元素的缩写。