计算两个模式之间的字符串出现次数 [英] Count the number of a string appearance between two patterns

查看:54
本文介绍了计算两个模式之间的字符串出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于这样的文本文件:

START_PATTERN

...TAG1...
...TAG2...
...TAG3...
...TAG4...
STOP_PATTERN

START_PATTERN
...TAG1...
...TAG5...
...TAG4...
...TAG1...
STOP_PATTERN

我想返回第一个块(在开始和结束之间),该块至少有2条TAG1和4条总行. 因此,这种情况下的结果将是:

I want to return the first block(between start and end) having at least 2 TAG1 and 4 total lines. So the result in this case would simply be:

START_PATTERN
...TAG1...
...TAG5...
...TAG4...
...TAG1...
STOP_PATTERN

我已经尝试过了:

   awk 'x {next}
      /START_PATTERN/
      {n=1;f=1;count=0}f {lines[n++]=$0}  
      /END_PATTERN/
      {if(n==4){/TAG1/count++;x=1}}  #the message should appear for 9 lines
      {print count}' file

谢谢!

推荐答案

您可以尝试以下awk脚本:

/START/{
    p=1; tag=0; tot=0;
    lines = "";
}
p{
    if ($0 ~ /TAG/)
        tot++;
    if ($0 ~ /TAG1/)
        tag++;
    lines = lines RS $0
}
/STOP/{
    p=0;
    if (tot == 4 && tag>=2)
        print lines;
}

这篇关于计算两个模式之间的字符串出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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