2017-02-24 81 views
0

我有一个文件夹,我想要做的是写一个shell脚本,它打印文件的名称以及这些文件中某个单词重复的次数。grep命令 - 文件名和每个文件中某个单词的重复次数打印在两列中

我的输出应该是这个样子:

filename 3 
filename 12 
filename 24 
… 

文件名不包括路径和扩展名的文件的名称即可。

我设法用一个for循环来做到这一点,但我认为,执行时间是不是很有效,所以我的其他想法是使用grep命令:

grep -c “word" */*.txt 

输出我得到这个样子的:

folder/filename.txt:3 

我试图使用cut命令,但我无法弄清楚如何避免减少单词出现在不同文件中的次数,并且文件名和数字之间必须有空格。

grep -c “word" */*.txt | cut -d'/' -f2 | cut -d'.' -f1 

任何想法如何用grep或其他替代方法做到这一点?

+1

请发布您的非工作代码及其输出。 – Fred

+0

https://i.stack.imgur.com/0jCJL.png – user408340

+0

输出:文件夹/文件名.txt:3 – user408340

回答

1

你用cut做了很好的努力。当您可以通过cut解决问题时,大多数情况下您都找到了一个可靠的快速解决方案。
在这种情况下,您需要修复cut命令会给出一个难看的结果。

# Ugly cutting 
grep -c "word" */*.txt | cut -d'/' -f2 | tr ':' '.' | cut -d"." -f1,3 | tr '.' ' ' 

固定cut是错在这里,但你可以学到很酷的事情

# going weird 
# Combine first colums 
grep -c "word" */*.txt | cut -d'/' -f2 | cut -d"." -f1 
# with second column 
grep -c "word" */*.txt | cut -d'/' -f2 | cut -d":" -f2 
# using paste and process substitution 
paste -d" " <(grep -c "word" */*.txt | cut -d'/' -f2 | cut -d"." -f1) <(grep -c "word" */*.txt | cut -d'/' -f2 | cut -d":" -f2) 

不,这不是解决这个问题的方法。使用sed

grep -c "word" */*.txt | sed 's#.*/##;s#\..*:# #' 
# or shorter 
grep -c "word" */*.txt | sed 's#.*/\([^.]*\).*:#\1 #' 
+0

非常感谢!我肯定从你的答案中学到了很多东西,但我会像你所建议的那样使用sed。:) – user408340

+0

@ user408340如果此答案解决了您的问题,请考虑通过单击复选标记来接受答案,以让其他人知道问题已解决。 –

+0

完成。谢谢。 :) – user408340

相关问题