awksed

Find between patterns and process between patterns


I have a file format like below,

####################### FILE Content ###################

Path 1
AND cell
OR1 cell
BUFF1 cell
OR2 cell
Ends

Path 2
OR1 cell
BUFF1 cell
AND1 cell
AND2 cell
BUFF2 cell
OR2 cell
Ends

Path 3
AND1 cell
AND2 cell
AND3 cell
OR1 cell
Ends

##########################################

I need output like below:

Path 1 - BUFF* count 1

Path 2 - BUFF* count 2

Path 3 - No BUFF

By using sed i can first get the Pattern to Pattern like. sed -n '/Path/,/Ends/p' Further to get the Ouput after that, i need your expertise help. can someone help me please.

Thanks GB


Solution

  • You might use awk and use patterns to check if you are between Path followed by a digit and Ends.

    When it matches Ends print the current Path you are in and the count of BUFF's.

    Then reset the variables seen and buff.

    awk '
    /^Path [0-9]+/{seen=1; buff=0; path=$0; next}
    {
      if(seen && $1 ~ /^BUFF[0-9]+$/){++buff;}
    }
    {
      if(seen && $1 ~ /^Ends$/){
        print path " - " (buff ? "BUFF* count " buff : "No BUFF")
        seen=0; buff=0    
      }
    }
    ' file
    

    Output

    Path 1 - BUFF* count 1
    Path 2 - BUFF* count 2
    Path 3 - No BUFF