J.E
J.E

Reputation: 35

Count the number of a string appearance between two patterns

For text file like this:

START_PATTERN

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

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

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

I have tried this:

   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

Thank you!

Upvotes: 0

Views: 69

Answers (3)

potong
potong

Reputation: 58420

This might work for you (GNU sed):

sed -nr '/START/{:a;N;/STOP/!ba;/(TAG1).*\1/!b;/([^\n]*TAG[^\n]*\n){4,}/!b;p;q}' file

Turn on seds grep-like nature and collect lines between START and STOP. If those lines collected contain two or more TAG1's and four or more TAG lines print and then abort.

Upvotes: 1

anubhava
anubhava

Reputation: 785156

Another working awk:

awk '/START_PATTERN/ {
   p=$0
   lines=1
   next
}
p != "" {
   p = p ORS $0
   lines++
}
/STOP_PATTERN/ && split(p,a,"TAG1")>2 && lines>=4 {
   print p
}' file

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

Upvotes: 1

sat
sat

Reputation: 14949

You can try this awk script:

/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;
}

Upvotes: 1

Related Questions