Is it possible to pretty print Awk's code?
Asked Answered
B

1

11

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?

Ballew answered 18/4, 2019 at 12:22 Comment(0)
B
16

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
}
Ballew answered 18/4, 2019 at 12:22 Comment(6)
Noice! But is there a counter operation for converting to one-liner?Clotildecloture
@JamesBrown piping to tr -d '\n' | tr -s ' ' (removing new lines and squeezing spaces) :PBallew
Out of humor, I cannot see @JamesBrown any option for this in the manual.Ballew
(tr '\n' ';' :) Yeah, me neither—then again I never saw the -o either... :DClotildecloture
@JamesBrown tr '\n' ';' would corrupt scripts with lines that end in `\`. So, thankfully, no :-). (or more accurately - it's non-trivial and let's not try to invent a one-liner generator!)Sorption
If you don't have GNU awk you can use a C beautifier (e.g. there's an online one at codebeautify.org/c-formatter-beautifier you can copy/paste the script BEGIN {print 1} END {print 2} into and it'll show the same output as gawk -o) to get an idea of a reasonable layout. It's not perfect but better than nothing.Sorption

© 2022 - 2024 — McMap. All rights reserved.