计算文件中某个模式出现的次数(即使在同一行) [英] Count number of occurrences of a pattern in a file (even on same line)

查看:20
本文介绍了计算文件中某个模式出现的次数(即使在同一行)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在搜索文件中某个字符串出现的次数时,我一般使用:

When searching for number of occurrences of a string in a file, I generally use:

grep pattern file | wc -l

但是,由于 grep 的工作方式,这每行只能找到一次.如何搜索字符串在文件中出现的次数,无论它们是在同一行还是不同行?

However, this only finds one occurrence per line, because of the way grep works. How can I search for the number of times a string appears in a file, regardless of whether they are on the same or different lines?

另外,如果我要搜索的是正则表达式模式,而不是简单的字符串怎么办?我如何计算这些,或者更好的是,在新行上打印每个匹配项?

Also, what if I'm searching for a regex pattern, not a simple string? How can I count those, or, even better, print each match on a new line?

推荐答案

要计算所有出现的次数,请使用 -o.试试这个:

To count all occurrences, use -o. Try this:

echo afoobarfoobar | grep -o foo | wc -l

当然还有 man grep (:

有些人建议只使用 grep -co foo 而不是 grep -o foo |wc -l.

Some suggest to use just grep -co foo instead of grep -o foo | wc -l.

不要.

此快捷方式并非在所有情况下都有效.手册页说:

This shortcut won't work in all cases. Man page says:

-c print a count of matching lines

这些方法的差异如下所示:

Difference in these approaches is illustrated below:

1.

$ echo afoobarfoobar | grep -oc foo
1

一旦在行中找到匹配项(a{foo}barfoobar),搜索就会停止.只有一行被检查并匹配,所以输出是1.实际上 -o 在这里被忽略了,你可以使用 grep -c 代替.

As soon as the match is found in the line (a{foo}barfoobar) the searching stops. Only one line was checked and it matched, so the output is 1. Actually -o is ignored here and you could just use grep -c instead.

2.

$ echo afoobarfoobar | grep -o foo
foo
foo

$ echo afoobarfoobar | grep -o foo | wc -l
2

在行 (a{foo}bar{foo}bar) 中找到两个匹配项,因为我们明确要求找到每个出现 (-o).每次出现都打印在单独的行上,wc -l 只计算输出中的行数.

Two matches are found in the line (a{foo}bar{foo}bar) because we explicitly asked to find every occurrence (-o). Every occurence is printed on a separate line, and wc -l just counts the number of lines in the output.

这篇关于计算文件中某个模式出现的次数(即使在同一行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆