awk Basic Examples

John John (304)
5 minutes

Learn the basics of awk with these simple examples. If you need more background information on the awk command, check out the guide What is awk?.

Posted in these interests:
h/unix13 guides
h/linux41 guides

For each example we're going to use the same data - a csv file with information about U.S. presidents:

1,George Washington,http://en.wikipedia.org/wiki/George_Washington,30/04/1789,04/03/1797,Independent,Virginia
2,John Adams,http://en.wikipedia.org/wiki/John_Adams,04/03/1797,04/03/1801,Federalist,Massachusetts
3,Thomas Jefferson,http://en.wikipedia.org/wiki/Thomas_Jefferson,04/03/1801,04/03/1809,Democratic-Republican,Virginia
...

Since we're using a csv file, we'll have to specify a field separator with the -F option.

Let's print just the presidents names only.

$ awk -F "," '{print $2}' presidents.csv
George Washington
John Adams
Thomas Jefferson
James Madison

Let's print the names of all of the presidents from Ohio by filtering for /Ohio/.

$ awk -F "," '/Ohio/ {print $2}' presidents.csv
William Henry Harrison
Ulysses S. Grant
Rutherford B. Hayes
James A. Garfield
William McKinley
William Howard Taft
Warren G. Harding

Let's do something similar as the previous example except we'll use the END cleanup action to print a summary.

$ awk -F "," '/Tennessee/ {print $2; ++n} END {print n, "presidents from Tennessee"}' presidents.csv
Andrew Jackson
James K. Polk
Andrew Johnson
3 presidents from Tennessee

Let's print only the presidents whose names have a total length less than 12 characters.

$ awk -F "," '{if (length($2) < 12) print $2}' presidents.csv
John Adams
John Tyler
Gerald Ford
A tabletop arcade cabinet full of Pi!
Ash Ash (362)
0

The Picade from Pimoroni brings new meaning to tabletop gaming. This tiny box is built for DIY gamers with a touch of class.