Skip to the workspace
Pebellslearn by building
Text Processing  ›  Capstone Project

grep and awk — Finding Lines and Working with Fields

grep 15 mingrep prints lines that match a pattern, and awk splits each line into fields and runs pattern-action rules, with END for totals.

linux / grep and awk — Finding Lines and Working with Fields

Explore each scene at your own pace.

01 · The rule

The rule

grep and awk — Finding Lines and Working with Fields

Everything in this section builds up to two tools you'll reach for daily. grep answers "which lines mention this?", across one file or a thousand. awk answers "from those lines, take these fields and do some arithmetic". Together they cover most quick questions you'll ever ask about text.

The rule

grep finds the lines; awk picks the fields and does the maths.

grep PATTERN FILE prints every line that contains the pattern:

$ grep chilli harvest.csv
2026-06-03,chilli,0.8,asha

The options you'll use most:

Option Does
-i ignore case, so TOMATO matches tomato
-v invert: print lines that do not match
-c print only the count of matching lines
-n show line numbers
-r search every file in a folder, recursively
-E extended patterns, such as basil or chilli written with a bar between them
-w match whole words only
$ grep -c tomato harvest.csv          # 3
$ grep -n chilli harvest.csv          # 5:2026-06-03,chilli,0.8,asha
$ grep -r "TODO" ~/garden             # every TODO in every file

awk reads a line at a time, splits it into fields $1, $2 and so on ($0 is the whole line), and runs a small program on it. -F, sets the separator. The program is written as a pattern and an action: condition { what to do }.

$ awk -F, '{ print $2 }' harvest.csv                  # like cut -d, -f2
$ awk -F, 'NR > 1 && $3 > 1 { print $4 }' harvest.csv   # who picked more than 1 kg
asha
ravi
meera
$ awk -F, '$2 == "tomato" { s += $3 } END { print s }' harvest.csv
9.6

END { ... } runs once, after the last line. That's where totals get printed. NR is the current line number, so NR > 1 skips the header. Without it, awk would compare the word kg with 1 as text, and the header's picker would sneak into the output. && means "and".

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.