
キャロットという単語を含むファイルの数を検索して表示します(大文字と小文字は区別されません)
今のところ、これが私の持っているものです。ただ、wc を追加して、carrot という単語を含むファイルがいくつあるかを数える方法がわかりません。
検索 . -exec grep -i carrot {} \;
答え1
まず、他の人が言っているように、 を使用する理由はありません。find
再帰的な を使用してください。grep
grep -irm 1 carrot . | wc -l
は、最初の一致の後に各ファイルの検索を停止する-m 1
ことを保証しますgrep
。これがないと、一致したファイルの数をカウントしません。ファイル含まれているcarrot
のは行、同じファイルに のインスタンスが複数含まれている場合、そのファイルは複数回カウントされますcarrot
。man grep
-r, --recursive
Read all files under each directory, recursively, following
symbolic links only if they are on the command line. This is
equivalent to the -d recurse option.
-i, --ignore-case
Ignore case distinctions in both the PATTERN and the input
files. (-i is specified by POSIX.)
-m NUM, --max-count=NUM
Stop reading a file after NUM matching lines.
本当にfindでやりたいなら、こうすればいい
find . -type f -exec grep -im 1 carrot {} \; | wc -l
-type f
ディレクトリは必要ないので指定していることに注意してくださいgrep
。
答え2
単語を含むファイルの数を調べるにんじん
number_of_files=`grep -l -r -i "carrot" . | wc -l`
引数の意味grep
:
-l, --files-with-matches
Only the names of files containing selected lines are written to standard output. grep will only search a file until a match has been found, making
searches potentially less expensive. Pathnames are listed once per file searched. If the standard input is searched, the string ``(standard
input)'' is written.
-R, -r, --recursive
Recursively search subdirectories listed.
-i : case insenstive
wc -l
: プログラムに入力として渡された行数を出力します。この場合、これらの行は によって見つかった入力パターンに一致するファイルの名前ですgrep
。
出力を印刷する
echo $number_of_files
答え3
smRajの解決策のバリエーションは、grepを2回呼び出すことです。次の例は、同じ結果になります。グレップ[等]| トイレ -l:
grep -l -r -i "carrot" . | grep -c .
次のようにすると、検索した単語を含むファイルの番号付きリストが出力されます。
grep -l -r -i "carrot" . | grep -n .