ファイル名に改行が含まれていない場合は、grepgrepで一致するファイルの名前を出力し、結果をカウントすることで、複数回の呼び出しを回避できます。
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)、2つの外部プロセスがあるためgrep、2つのファイルを個別に実行することもできます。(grepvs.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]}、最初の配列要素の省略形です。