bash 递归 Grep 仅显示总匹配计数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16126808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:14:03  来源:igfitidea点击:

Recursive Grep to show only total matchin count

bashshellgrep

提问by Mena Ortega

I'm trying to do a recursive grep search such as:

我正在尝试进行递归 grep 搜索,例如:

grep -r -c "foo" /some/directory

which give me output auch as:

这给了我输出,例如:

/some/directory/somefile_2013-04-08.txt:0
/some/directory/somefile_2013-04-09.txt:1
/some/directory/somefile_2013-04-10.txt:4
...etc

however, I would like to just get the total number of matches in all files, like:

但是,我只想获取所有文件中的匹配总数,例如:

Total matches:    5

I've played around with some other examples such as in this thread, although I can't seem to do what should be so simple.

我玩过一些其他的例子,比如在这个线程中,虽然我似乎无法做应该这么简单的事情。

回答by Halim Qarroum

grep -ro "foo" /some/directory | wc -l | xargs echo "Total matches :"

The -ooption of grepprints allthe existing occurences of a string in a file.

-o的选项grep打印所有文件中的字符串的存在出现次数。

回答by dkmike

Just pipe to grep.

只需管道到grep。

grep -r "foo" /some/directory | grep -c "foo"

回答by John Kugelman

matches=$(grep -rch "foo" /some/directory | paste -sd+ - | bc)
echo "Total matches: $matches"

The paste/bc piece sums up a list of numbers. See: Bash command to sum a column of numbers.

paste/bc 部分总结了一个数字列表。请参阅:对一列数字求和的 Bash 命令

回答by btanaka

If you only need the total, you can skip getting the count for each file, and just get a total number of matched lines:

如果您只需要总数,则可以跳过获取每个文件的计数,而只获取匹配行的总数:

grep -r "foo" /some/directory | wc -l