Awk and the Advent of Code

I’ve been participating in this year’s Advent of Code (AoC). I’m using GNU Awk as usual. Awk is perfect for these puzzles so far: easy input parsing and no need (yet) for fancy function libraries. The main benefit for me of participating, other than feeling part of a community of coders, is learning from other people’s algorithm and language usage, via Reddit and Github. Some of the more surprising syntax that I have seen has been practiced as part of code golfing - finding ways to drastically shorten code and arrange it in artistic blocks. I thought I’d share here some of the new Awk usages I’ve seen.

1. Missing elements in for( ; ; )

The initialization and increment arguments can be omitted:

for ( ; ++i < 10; ) 
  print i

2. Output via default action

The default action in the line-by-line phase is to print $0. Any pattern that evaluates to TRUE will cause this default action:

$ echo a | gawk '1'  # gives: a

Logical tests:

$ echo a | gawk '1&&0'  # no output
$ echo a | gawk '1&&1'  # gives a

Assignment statement evaluate to their assignment value which may be TRUE too (if not 0 or ""), and $0 can be changed within them:

$ echo "a b" | gawk '$0=$2'  # gives: b

This can save the 5+1 characters of print when golfing! Thanks to @azzal07 for this and many of the other tips.

3. Evaluated variables as input fields

I knew you can use $i as a variable input field, but had not noticed that $(y+x), etc, works and can thus save a variable. Thanks to @djkirby.