Search code examples
unixawksedtext-processing

Loop and process over blocks of lines between two patterns in awk?


This is actually a continued version of thisquestion:

I have a file

1
2
PAT1
3    - first block
4
PAT2
5
6
PAT1
7    - second block
PAT2
8
9
PAT1
10    - third block

and I use awk '/PAT1/{flag=1; next} /PAT2/{flag=0} flag' to extract the blocks of lines.

Extracting them works ok, but I'm trying to iterate over these blooks in a block-by-block fashion and do some processing with each block (e.g. save to file, process with other scripts etc.).

How can I construct such a loop?


Solution

  • Problem is not very clear but you may do something like this:

    awk '/PAT1/ {
       flag = 1
       ++n
       s = ""
       next
    }
    /PAT2/ {
       flag = 0
       printf "Processing record # %d =>\n%s", n, s
    }
    flag {
       s = s $0 ORS
    }' file
    
    Processing record # 1 =>
    3    - first block
    4
    Processing record # 2 =>
    7    - second block