⤺ /text/useful


AWK is great for processing text, extracting data from
text, etc. and is installed on most Unix or Unix-like

An AWK program works like so:

    condition { action }
    condition { action }

But in a one-liner scenario, you'd tend to just have
one condition.


All examples below are one-liners with the program
included on the line. However, you can also specify
programs within external files and load them in with
the -f option:

    awk -f program.awk input.txt

Just reprints the source document
    awk '{print}' a.txt

As printing is the default action, you can also just
have a condition such as to print all lines with length
over 15:
    awk 'length($0) > 15 {print}' a.txt
    awk 'length($0) > 15' a.txt

awk breaks all lines into 'fields' with space being the
default so this prints the second word on each line
    awk '{print $2}' a.txt

As above but only for lines that match the 'test' regex
    awk '/test/{print $1}' a.txt

As above but only for lines that match the 'test' regex
with no newline
    awk '/test/{printf $1}' a.txt

Breaks lines into 'fields' with : as separator instead
    awk -F":" '{print $2}' a.txt

Like above but print only IF there is a second field
    awk -F":" '{if ($2) print $2}' a.txt

Print final field only
    awk -F":" '{print $NF}' a.txt

Delete the first field then print the line
    awk -F":" '{$1 = ""; print}' a.txt

Print from the line that matches first regex until the
second. Note that the default act of printing is implied
    awk '/start/,/stop/' a.txt