2012-03-31 43 views
1

我想幫助我的女朋友 - 她需要200個文件(每個文件)中特定字符的具體計數。使用unix shell計算多個文件中字符的出現次數

我已經找到How can I use the UNIX shell to count the number of times a letter appears in a text file?,但只顯示完整的數字,而不是每個文件的出現次數。基本上,我想要的是以下內容:

$ ls 
test1 test2 
$ cat test1 
ddddnnnn 
ddnnddnnnn 
$ cat test2 
ddnnddnnnn 
$ grep -o 'n' * | wc -w 
16 
$ <insert command here> 
test1 10 
test2 6 
$ 

或類似的輸出。因爲這將在她的大學機器上,我不能在perl中編寫任何代碼,所以只允許shell。我的外殼知識有點生疏,所以我不能想出更好的解決方案 - 也許你可以提供幫助。

回答

2
grep -Ho n * | uniq -c 

產生

10 test1:n 
    6 test2:n 

如果你想要的是你的輸出:

grep -Ho n * | uniq -c | while read count file; do echo "${file%:n} $count"; done 
0

這不完全優雅,但最明顯的解決方案是:

letter='n' 
for file in *; do 
    count=`grep -o $letter "$file" | wc -w` 
    echo "$file contains $letter $count times" 
done 
+1

'用於*'文件移位6優選'在$(LS)文件' - http://mywiki.wooledge.org/ParsingLs – 2012-03-31 17:28:49

+0

對,糾正,thx,+1 – tchap 2012-03-31 19:47:11

0

格倫的回答對於U的口味來說要好得多支持它的NIX。這將適用於聲稱符合POSIX標準的UNIX。這是爲那些其他答案不會飛的窮人而設。 POSIX grep沒有任何說明grep -H -o請參閱:http://pubs.opengroup.org/onlinepubs/009604499/utilities/grep.html

獲取您要將其稱爲list.txt的文件列表。我選擇了字符^ ==無故

while read fname 
do 
    cnt=`tr -dc '^' < $fname | wc -c` 
    echo "$fname: $cnt" 
done < list.txt 
相關問題