Linux

How to use the awk command in Linux, with examples

How the awk command reads text line by line, splits it into fields like $1, picks lines with patterns, sums columns with END and changes separators with -F.

  • 6 min read
  • 5 questions
  • +35 XP
Transcript

awk, explained by cats. Kitty runs a tuna shop. Every order goes into one long file. Who ordered, which fish, how many. Today she only wants the names. awk reads a file one line at a time. It cuts each line into fields, wherever there's a space.

Dollar one is the first field. Dollar two is the second. So Kitty types awk, print dollar one. Every name. Nothing else. Now only the big orders. She puts a pattern in front: dollar three greater than ten. awk runs the action only on lines that match.

How many fish did she sell? She adds each dollar three to a sum, then prints it at the end. A hundred and fifty-six fish. Her other file uses commas? Dash F comma, and awk cuts at the commas instead. That's awk. A pattern and an action, for every line. And no, it's not short for awkward.