Gnu Awk: One-line Examples
Last updated:Table of Contents
- Print Nth column
- Print where line matches
- Print where line matches regex
- Print where line does not match regex
- Custom delimiter
- Regexp delimiter
- Print all columns from Nth to last
- Use shell variables
Print Nth column
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 where line matches
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
Print where line matches regex
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
Print where line does not match regex
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
orY
:$ echo "fooXXbarYYbXaz" | awk -F '[X|Y]{2,}' '{print $3}' bXaz
Print all columns from Nth to last
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