且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何计算文件中字符串的出现次数?

更新时间:2022-11-07 23:30:08

这将输出包含您的搜索字符串的的数量.

This will output the number of lines that contain your search string.

grep -c "echo" FILE

但是,这不会计算文件中的出现次数(即,如果您在一行上多次回显).

This won't, however, count the number of occurrences in the file (ie, if you have echo multiple times on one line).

经过一番摸索,您可以使用下面这些肮脏的代码来获取出现的次数:

After playing around a bit, you could get the number of occurrences using this dirty little bit of code:

sed 's/echo/echo\n/g' FILE | grep -c "echo"

这基本上在每个echo实例之后添加一个换行符,因此它们每个都在自己的行上,从而使grep可以对这些行进行计数.例如,如果您只想要单词"echo"而不是"echoing",则可以优化正则表达式.

This basically adds a newline following every instance of echo so they're each on their own line, allowing grep to count those lines. You can refine the regex if you only want the word "echo", as opposed to "echoing", for example.