Use awk to insert a line after N output

The problem with your attempted solution is that awk's NR is a count of the input records, whereas you want to insert the newline based on the count of the number of output records.

I don't think awk keeps such a count natively, but you could do something like

awk '/pattern1|pattern2|pattern3/ {print; if (++onr%3 == 0) print ""; }' infile

in which we define a new variable onr (for output number of record - the variable name is arbitrary) and increment it every time we match/print the wanted text, then check if that is divisible by 3 and if so print a newline.

Tags:

Awk