10

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?

fedorqui
  • 275,237
  • 103
  • 548
  • 598

1 Answers1

14

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
}
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 1
    Noice! But is there a counter operation for converting to one-liner? – James Brown Apr 18 '19 at 13:06
  • @JamesBrown piping to `tr -d '\n' | tr -s ' '` (removing new lines and squeezing spaces) :P – fedorqui Apr 18 '19 at 13:07
  • 1
    Out of humor, I cannot see @JamesBrown any option for this in the manual. – fedorqui Apr 18 '19 at 13:24
  • (`tr '\n' ';'` :) Yeah, me neither—then again I never saw the `-o` either... :D – James Brown Apr 18 '19 at 13:43
  • 2
    @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!) – Ed Morton Apr 18 '19 at 15:25
  • 3
    **If you don't have GNU awk** you can use a C beautifier (e.g. there's an online one at https://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. – Ed Morton Apr 18 '19 at 15:41