
我應該找到並顯示包含單字“carrot”的檔案數量(忽略大小寫)
到目前為止,這就是我所擁有的,我只是不確定如何將 wc 添加到其中來計算有多少個包含“胡蘿蔔”一詞的文件
尋找 。 -exec grep -i 胡蘿蔔 {} \;
答案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。以下將給出相同的結果grep[ETC]|廁所-l:
grep -l -r -i "carrot" . | grep -c .
下面將列印包含搜尋單字的檔案的編號清單。
grep -l -r -i "carrot" . | grep -n .