Search code examples
awkgnupretty-print

Is it possible to pretty print Awk's code?


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?


Solution

  • 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
    }