Gnu Awk: One-line Examples

Last updated:
Table of Contents

By default, awk uses one or more spaces as the default column delimiter:

  • print the second column:

    $ echo "foo   bar baz" | awk '{print $2}'
    bar
    
  • print Nth column when the line contains a string (anywhere):

    create a file input1.txt like this:

    foo 1
    bar 2
    baz 3
    quf 4
    

    and pipe it to the awk command:

    cat input1.txt | awk '/fo/ {print $2}'
    1
    

See all regexp operators here: Regexp operators

  • Print Nth column for lines starting with "f":

    # input1.txt
    foo 1
    bar 2
    baz 3
    quf 4
    
    $ cat input1.txt | awk '$0 ~ /^f/ {print $2}'
    1
    

Use !~ instead:

  • Print Nth column for lines NOT starting with "f"

    # input1.txt
    foo 1
    bar 2
    baz 3
    quf 4
    
    $ cat input1.txt | awk '$0 !~ /^f/ {print $2}'
    2
    3
    4
    

Custom delimiter

Use -Fdelimiter

$ echo "foo,bar,baz" | awk -F, '{print $2}'
bar

Regexp delimiter

  • split on two or more dashes (note that ba-z was not split)

    $ echo "foo---bar--ba-z" | awk -F '-{2,}' '{print $3}'
    ba-z
    
  • split on two or more occurrences of X or Y:

    $ echo "fooXXbarYYbXaz" | awk -F '[X|Y]{2,}' '{print $3}'
    bXaz
    
Twitter Linkedin YC Hacker News Reddit
  • Example: Print all columns from 4th to last

    $ echo 'foo,bar,baz,quux,bax' | awk -F, '{ print substr($0, index($0,$4)) }'
    quux,bax
    

Use shell variables

Use -v modifier.

# input1.txt
foo 1
bar 2
baz 3
quf 4

In this example: print the contents of myvar plus the second column for every line:

$ myvar='foobar'
$ cat input1.txt | awk -v var="$myvar" '{print var " " $2}'
foobar 1
foobar 2
foobar 3
foobar 4


References

Dialogue & Discussion