Ed Morton showed me that GNU awk has the -o
option to pretty print:
GNU Awk User's Guide, on Options
-o[file]
--pretty-print[=file]
Enable pretty-printing of awk programs. Implies --no-optimize
. By default, the output program is created in a file named awkprof.out
(see Profiling). The optional file argument allows you to specify a different file name for the output. No space is allowed between the -o
and file, if file is supplied.
NOTE: In the past, this option would also execute your program. This is no longer the case.
So the key here is to use -o
, with:
- nothing if we want the output to be stored automatically in "awkprof.out".
-
to have the output in stdout.
file
to have the output stored in a file called file.
See it live:
$ gawk -o- 'BEGIN {print 1} END {print 2}'
BEGIN {
print 1
}
END {
print 2
}
Or:
$ gawk -o- 'flag{ if (/PAT2/){printf "%s", buf; flag=0; buf=""} else buf = buf $0 ORS}; /PAT1/{flag=1}' file
flag {
if (/PAT2/) {
printf "%s", buf
flag = 0
buf = ""
} else {
buf = buf $0 ORS
}
}
/PAT1/ {
flag = 1
}