AWK Tutorial

14th of March, 2021
linux, ops

awk is the mighty sword when we need to handle text. Here is a quick intro video.
by Tom Rothe

sed Tutorial

Today, we are learning a new programming language called awk. awk is useful to filter text. So it reads text in and spits out a processed version. For example, it can be used to extract a column from a CSV or analyze a log file.

So let’s give awk a go.

Quick notes

awk 'pattern1 { action1; action2; }'
awk 'pattern2 { action3; } # comment'
awk -f somescript.awk input.txt
cmd | awk 'pattern1 { action1; action2; }'
/admin/ { ... }     # any line that contains 'admin'
/^admin/ { ... }    # lines that begin with 'admin'
/admin$/ { ... }    # lines that end with 'admin'
/^[0-9.]+ / { ... } # lines beginning with series of numbers and periods
/(POST|PUT|DELETE)/ # lines that contain specific HTTP verbs
debug == true
counter != 23
string ~ /regex/

print "some output"    #
substr($1, 1, 3)       # mind that $1 is the whole match from the pattern
sin(77), strftime('%H:%M', systime())        # other functions
x = 1                  # assign variables
if, for, break, next   # control statements

{ print $0; }  # prints $0. In this case, equivalent to 'print' alone
{ exit; }      # ends the program
{ next; }      # skips to the next line of input
{ a=$1; b=$0 } # variable assignment
{ c[$1] = $2 } # variable assignment (array)