简体   繁体   English

使用 sed 或 grep 在一行中计算正则表达式模式匹配?

[英]Counting regex pattern matches in one line using sed or grep?

I want to count the number of matches there is on one single line (or all lines as there always will be only one line).我想计算一行上的匹配数(或所有行,因为总是只有一行)。

I want to count not just one match per line as in我想计算的不仅仅是每行一场比赛

echo "123 123 123" | grep -c -E "123" # Result: 1

Better example:更好的例子:

echo "1 1 2 2 2 5" | grep -c -E '([^ ])( \1){1}' # Result: 1, expected: 2 or 3

You could use grep -o then pipe through wc -l :您可以通过wc -l使用grep -o然后 pipe :

$ echo "123 123 123" | grep -o 123 | wc -l
3

Maybe you should convert spaces to newlines first:也许您应该首先将空格转换为换行符:

$ echo "1 1 2 2 2 5" | tr ' ' $'\n' | grep -c 2
3

Why not use awk?为什么不使用 awk? You could use awk '{print gsub(your_regex,"&")}' to print the number of matches on each line, or awk '{c+=gsub(your_regex,"&")}END{print c}' to print the total number of matches.您可以使用awk '{print gsub(your_regex,"&")}'打印每行的匹配数,或awk '{c+=gsub(your_regex,"&")}END{print c}'打印匹配的总数。 Note that relative speed may vary depending on which awk implementation is used, and which input is given.请注意,相对速度可能会有所不同,具体取决于使用的 awk 实现以及给出的输入。

This might work for you:这可能对您有用:

sed -n -e ':a' -e 's/123//p' -e 'ta' file | sed -n '$='

GNU sed could be written: GNU sed 可以写成:

sed -n ':;s/123//p;t' file | sed -n '$='

Maybe below:也许在下面:

echo "123 123 123" | sed "s/123 /123\n/g" | wc -l

( maybe ugly, but my bash fu is not that great ) (也许丑,但我的 bash fu 不是那么好)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM