在 list.txt 我有:
Lucas
Viny
Froid
在當前目錄中,我有很多包含名稱的 csv 檔案。
我需要知道串列中的每個單詞在這些 csv 檔案中出現的次數。
我試過:
grep -riohf list.txt . | wc -lw
但它只回傳計數。我需要知道每個計數指的是哪個詞。
我只需要這樣的東西:
Lucas 353453
Viny 9234
Froid 934586
uj5u.com熱心網友回復:
假設你有這些檔案:
$ cat list.txt
Lucas
Viny
Froid
$ cat 1.csv
Lucas,Viny,Bob
Froid
$ cat 2.csv
Lucas,Viny,Froid
Lucas,Froid
您可以使用以下內容awk來計算與串列匹配的欄位:
awk -F ',' 'FNR==NR{cnt[$1]; next}
{for (i=1; i<=NF; i ) if ($i in cnt) cnt[$i] }
END{for (e in cnt) print e, cnt[e]}' list.txt {1..2}.csv
Viny 2
Lucas 3
Froid 3
另一種方法是使用管道來計算 uniq 欄位:
cat {1..2}.csv | tr , "\n" | sort | uniq -c
1 Bob
3 Froid
3 Lucas
2 Viny
那么grep:
cat {1..2}.csv | tr , "\n" | grep -Fxf list.txt | sort | uniq -c
3 Froid
3 Lucas
2 Viny
uj5u.com熱心網友回復:
在回圈中使用grep和wc,您可以計算單詞的每個單獨出現次數,而不僅僅是行數。
while read -r line; do
count=$(grep -o "$line" *.csv | wc -l)
echo "$line $count"
done < list.txt
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/360644.html
