Gawk usage

From wikinotes

Awk is a versatile glue language, and it can be used in a few ways.



by default, each space-separated item on stdin is an argument.
you can use this to quickly extract space separated lines.

echo 'aa bb cc' | awk '{print $2}'  # bb

you can also choose the token used to split the string

echo 'aa|bb|cc' | awk -F'|' '{print $2}'  # bb

multiline matching

Match a line, then return N words afterwards.

# Find the line state UP, then print the line 2 lines afterwards
# (each 'getline' returns the next line)
ip addr | awk '/state UP/ { getline; getline; print $0 }'


awk is useful on it's own, for it's ability to do floating point math in bash.

awk 'BEGIN {print 1.5 / 2}'  # 0.75


run an awk file from interpreter

awk -f file.awk [arg..]  # run awk script

Or use a shebang to indicate script runs in awk

#!/usr/bin/env awk -f
# foo.awk

and run it directly