AI Hints
Home›Linux Tutorial›Changing Text
Linux · Lesson 51 of 120

awk: Working with Columns

Print the fields you want.

⏱ 2 min read▶ Video at 1:05:24🎓 Free
Watch this lesson in the Linux courseWatch on YouTube ↗Full Linux course

Cut is great for simple columns. But awk is like cut with superpowers. It understands columns automatically, and it can do maths and make decisions about each line.

awk: Working with Columns
From the video: awk: Working with Columns
  • cut, with superpowers
  • Columns automatically
  • Maths and decisions

Printing columns

In awk, dollar one means the first column, dollar two the second, and so on. Awk splits on spaces by default. So awk, print dollar four, prints the user from each log line. Print dollar three and dollar four prints the level, and the user.

Terminal
head -n 3 logs/server.log | awk '{print $4}'
priya
sam
sam
head -n 3 logs/server.log | awk '{print $3, $4}'
ERROR priya
INFO sam
INFO sam

Filtering with a condition

Awk can test each line before printing it. Here, only lines where column three is ERROR, and we print the time and the user. Dash capital F sets a different separator, like a comma for CSV files. Here, everyone who lives in London.

Terminal
awk '$3 == "ERROR" {print $2, $4}' logs/server.log
09:00:23 priya
09:07:00 jo
09:09:18 priya
09:11:08 priya
09:17:21 alex
09:17:56 alex
09:23:28 priya
awk -F, '$3 == "London" {print $1}' team.csv
sam
priya

When to use which

Here's a simple rule. To search for lines, use grep. To pick a column, use cut, or awk. To replace text, use sed. And when you need a condition, or a little maths, reach for awk. You don't need to master awk. Just knowing print dollar N will take you a long way.

keyvalue
grepfind lines
cut / awkpick columns
sedreplace text
awkconditions and maths

Summary

Awk prints columns with dollar one, dollar two, and can filter lines with conditions. Next, what to do with error messages.

Key takeaways
  • awk '{print $1}'
  • awk -F,
  • awk '$3 == "X"'
Next up: Redirecting Errors — 2> and /dev/null