Search code examples
awkgawknawk

Adding a delimiter after each file processed within awk


I have multiple files where I am extracting text between two delimiters (START and END non-inclusive). After I process each file I want to output a delimiter indicating the file was processed, say the string "END". How would I add the string "END" to the output after each processed file? For example,

Say I have two files with the content

file1.txt

line 1
line 2
START
I want to extract this text
and this text
END
line 3
line 4

and

file2.txt

line10
line20
START
I also want this text.
END
line 30

I know if I execute the following:

awk '/START/,/END/{if (!/START/&&!/END/) print}' test*.txt

I will get the following output:

I want to extract this text
and this text
I also want this text.

But the output I want is:

I want to extract this text
and this text
END
I also want this text.
END

How do I get the string "END" added to the output after each file is processed?


Solution

  • FNR==1 && NR!=1 {print "END"}
    END {print "END"}
    

    So you'd have:

    awk 'FNR==1 && NR!=1 {print "END"} /START/,/END/{if (!/START/&&!/END/) print} END {print "END"}' test*.txt