2012-03-31 44 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 
相关问题