我的幾個子資料夾中有很多文件,其中包含一個字串type="abc_
- 我不太確定有多少個變體- 所以我想知道我的文件中出現了abc_
多少次未知的情況。type="abc_
我希望得到類似包含行的東西
"type="abc_0815 found 50 times
"type="abc_0816 found 32 times
...
and so on.
如果我這樣做的話:
grep -rni 'type="abc_' * | wc
我已經知道它出現了 14905 次type="abc_
。
有人可以幫我嗎?
答案1
這用於find
獲取文件列表,將其傳遞給cat
並解析輸出awk
:
find . -type f |
xargs -I xx cat "xx" | awk '/type="abc_/{
for(i=1;i<=NF;i++){
if($i~/type="abc_/){ d[$i]++ } } }
END{ for(i in d){ print i"\tfound",d[i],"times." } }'
type="abc_4 found 1 times.
type="abc_3 found 2 times.
type="abc_6 found 1 times.
type="abc_2 found 2 times.
type="abc_10 found 3 times.
type="abc_5 found 1 times.
它使用 find 而不是簡單的查找內容,cat *
以便更靈活地搜尋內容。
xargs .. cat | ..
可以縮短為find . -type f -exec cat {} + | awk ..
答案2
只需添加-c
標誌即可讓 grep 為您計數。
如果 0 結果太多,可以用 awk 過濾掉
grep -rnic 'type="abc_' * | awk -F: '$NF>0'
答案3
嘗試類似這樣:
grep -rni 'type="abc_' * |sed -n "s/.*\(abc_[0-9]*\).*/\1/p"|uniq -c| sed "s/\(.*\)\(abc.*\)/\2 found \1 times/"