Quite often I find myself writing Awk one-liners that gain complexity over time.
I know I can always create an Awk file where to keep adding use cases, but it is certainly not as usable as changing the text on the command line.
For this: is there any way I can pretty print Awk's code, so I can make more sense out of it?
For example, given this:
awk 'flag{ if (/PAT2/){printf "%s", buf; flag=0; buf=""} else buf = buf $0 ORS}; /PAT1/{flag=1}' file
How can I get something a bit more readable?
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 namedawkprof.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:
-
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With