使用bash计算字符串中子字符串的出现次数(count no of occurences of a substring in a string using bash)

编程入门 行业动态 更新时间:2024-10-25 10:33:51
使用bash计算字符串中子字符串的出现次数(count no of occurences of a substring in a string using bash)

计数为2时,模式在字符串中出现三次

echo "axxxaaxx" | grep -o "xx" | wc -l echo "axxxaaxx" | grep -o "xx"

It is giving count as 2 where as pattern occurred thrice in the string

echo "axxxaaxx" | grep -o "xx" | wc -l echo "axxxaaxx" | grep -o "xx"

最满意答案

使用-P将启用支持外观的 PCRE:

echo "axxxaaxx" | grep -P '(?<=x)x'

在这种情况下,我们使用lookbehind,这意味着我们将匹配在它之前有x 。 这使我们能够重叠匹配:

如何“评估”正则表达式:

xxx ^^ |Cursor Looking for x on this position, since there is nothing this will not match xxx ^^ |Cursor Looking for x on this position since it's found we got a match xxx ^^ |Cursor Looking for x on this position since it's found we got a match

Using -P will enable PCRE which supports lookarounds:

echo "axxxaaxx" | grep -P '(?<=x)x'

In this case we are using a lookbehind which means that we will match an x which have an x before it. This makes us able to have overlapping matches:

How the regex is "evaluated":

xxx ^^ |Cursor Looking for x on this position, since there is nothing this will not match xxx ^^ |Cursor Looking for x on this position since it's found we got a match xxx ^^ |Cursor Looking for x on this position since it's found we got a match

更多推荐

本文发布于:2023-08-04 06:57:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1412436.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   中子   次数   bash   string

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!