grep, sed, awk -- Text Processing

grep, sed, awk -- Text Processing in Bash: --- Picture a records-processing bureau in the days before computers.


The Analogy: The Records Bureau's Conveyor of Specialist Desks

Picture a records-processing bureau in the days before computers. A stack of paper sheets -- claim forms, meter readings, order slips -- is placed on a conveyor and travels down a long bench past a row of specialist desks. Each clerk at the bench does exactly one job, extremely well, and does nothing else. A sheet arrives, the clerk acts on it, and it moves on to the next desk. Nobody at the bench tries to do the whole job alone; the power of the bench comes from arranging the right specialists in the right order.

The first specialist is the search clerk. Their only skill is deciding, for each sheet that passes, whether it mentions a particular phrase -- and if it does, letting it through, and if it does not, dropping it in the bin. They never change a word on a sheet; they only keep or discard. This is grep. Next along is the correction clerk. This clerk takes each sheet and rewrites parts of it as it passes: striking out a line, substituting one phrase for another, deleting a heading. They work one sheet at a time and never hold the whole stack. This is sed, the stream editor.

The last specialist is the ledger clerk. This clerk treats every sheet as a form with numbered columns, reads only the fields that matter, keeps running tallies in their head, and at the very end writes a single summary sheet -- totals, counts, one line per group. This is awk. The conveyor itself is the shell pipe, |: it carries the output of one desk to the input of the next. You choose which desks to place, and in what order, to suit the job; each desk sees only what the previous desk passed along, never the original stack.

The failures at this bench are failures of using the wrong specialist or forgetting how the conveyor works. You can bully the search clerk into doing arithmetic or the correction clerk into tabulating, but the result is slow, fragile, and easy to get wrong -- each clerk is sharp only at their own task. More subtly, the conveyor is one-directional and streaming: no desk sees the whole stack at once unless it is specifically told to hold everything, so a job that needs the complete picture -- sorting, counting distinct values -- needs a desk built to accumulate. And if the correction clerk changes a sheet's column layout, the ledger clerk downstream, who counts on fixed columns, silently tallies the wrong numbers. This lesson introduces the three specialists so that later lessons can drill into each.


Syntax or Core Structure

Each tool does one job: grep selects lines, sed edits lines, awk computes over fields. They shine when composed with a pipe. Consider a headerless file orders.csv of region,amount,status:

# orders.csv
north,120,ok
south,80,fail
north,200,ok
east,50,ok
south,90,ok

This one pipeline uses all three: grep keeps only the successful orders, sed strips the now-redundant status field, and awk counts the rows and sums the amounts.

grep 'ok$' orders.csv | sed 's/,ok$//' | awk -F, '{ total += $2 } END { print "orders:", NR; print "total:", total }'

Output:

orders: 4
total: 460

Read the pipeline left to right, as sheets moving down the bench. grep 'ok$' passes the four lines ending in ok and bins the fail line. sed 's/,ok$//' rewrites each surviving line to drop the trailing ,ok. awk -F, '...' splits each line on commas, adds column two into total, and in its END block -- run once after the last line -- prints the count (NR, the number of records) and the sum. No single tool did the whole job; the composition did.


Technical Depth: Three Specialists, One Bench

grep -- select whole lines

grep PATTERN [file] prints the lines that match a pattern and discards the rest. It never alters a line; it only keeps or drops. The pattern is a regular expression, so ok$ means "ok at end of line". Common flags are -c (count matches instead of printing them), -v (invert: print non-matching lines), -i (ignore case), and -n (show line numbers).

grep -c 'ok$' orders.csv
grep 'fail$' orders.csv | cut -d, -f1

Output:

4
south

The first command counts the successful orders; the second finds the failing line and shows only its region field. grep decides membership; it is the search clerk keeping or binning each sheet.

sed -- edit a stream line by line

sed 'SCRIPT' [file] applies an editing script to each line as it flows past. Its workhorse is substitution, s/find/replace/, with a trailing g to replace every occurrence on the line rather than just the first. sed reads one line at a time and never buffers the whole file, which is why it handles inputs of any size.

sed 's/ok$/OK/' orders.csv

Output:

north,120,OK
south,80,fail
north,200,OK
east,50,OK
south,90,OK

Every line ending in ok had it rewritten to OK; the fail line was passed through untouched because the pattern did not match. sed is the correction clerk, rewriting sheets as they pass.

awk -- compute over fields

awk -F, 'PROGRAM' splits each line into fields (here on commas, via -F,) and runs a program against them. Fields are $1, $2, and so on; NR is the current record number; a { ... } block runs per line and an END { ... } block runs once at the end. awk keeps state between lines, which is what lets it total, count, and group.

grep 'ok$' orders.csv | awk -F, '{ s[$1] += $2 } END { for (r in s) print r, s[r] }' | LC_ALL=C sort

Output:

east 50
north 320
south 90

Here awk accumulates the ok amounts into an associative array s keyed by region, then in END prints one line per region. The order in which for (r in s) walks an associative array is unspecified, so the output is piped through LC_ALL=C sort to make it deterministic -- a habit worth forming any time awk emits grouped results.

Selecting by presence or absence

The same set of lines can often be reached from either direction, and knowing both keeps pipelines short. To keep the successful orders you can either match what you want with grep or delete what you do not want with sed. These two commands produce the identical result on orders.csv:

grep -v 'fail$' orders.csv
sed '/fail/d' orders.csv

Output:

north,120,ok
north,200,ok
east,50,ok
south,90,ok

grep -v inverts the match and prints every line that does not end in fail; sed '/fail/d' addresses the lines that contain fail and deletes them. When you want several alternatives at once, grep -E takes an extended pattern with | meaning "or", so grep -E 'north|east' orders.csv selects the northern and eastern rows in one pass. Choosing the direction that reads most naturally for the task -- keep these, or drop those -- is part of writing pipelines a colleague can follow.

Which specialist for which job

ToolOne-line jobSees input asReach for it when
grepkeep or drop whole lineslines of textyou want only the matching rows
sedrewrite lines in placeone line at a timeyou need find-and-replace or line deletion
awkcompute over columnsfields per recordyou need totals, counts, or per-group summaries

The rule of thumb from the bench: if you are selecting rows, that is grep; if you are changing text within rows, that is sed; if you are doing arithmetic or grouping across columns, that is awk. Many real one-liners use two or three together, each doing the part it is best at.


Real World Example: A Regional Sales Report

A finance team keeps a scrappy sales.csv: a comment line at the top, region names wrapped in quotes, and a status field where only paid rows should count. The task is a per-region total and a grand total of paid sales. This report.sh filters with grep, cleans with sed, and tabulates with awk.

# sales.csv
# regional sales, do not edit by hand
"north",120,paid
"south",80,void
"north",200,paid
"east",50,paid
"south",90,paid
"west",40,refund
"east",60,paid
#!/usr/bin/env bash
# report.sh
set -euo pipefail

FILE="${1:-sales.csv}"

paid="$(grep 'paid$' "$FILE" | sed 's/"//g')"

echo "$paid" | awk -F, '{ s[$1] += $2 } END { for (r in s) print r, s[r] }' | LC_ALL=C sort
echo "---"
echo "$paid" | awk -F, '{ t += $2 } END { print "TOTAL", t }'

Running bash report.sh prints:

Output:

east 110
north 320
south 90
---
TOTAL 520

The pipeline mirrors the bench exactly. grep 'paid$' keeps only the lines ending in paid, which discards the comment line, the void row, and the refund row in one stroke. sed 's/"//g' strips every double quote so the region names are clean keys. The filtered, cleaned text is captured once into paid and fed to awk twice: first to sum amounts per region into the array s (sorted afterwards for a stable order), then to add every amount into a single running total t.

Reusing the paid variable rather than re-running grep and sed keeps the two summaries consistent: both see identical input, so the per-region figures always add up to the grand total. Each stage is independently testable -- you can run just the grep, or the grep | sed, and inspect what the next desk will receive. That inspectability is the practical payoff of composing small tools instead of writing one dense program. It also makes the script easy to grow: adding a count of orders per region, or a filter by minimum amount, means inserting one more stage rather than rewriting a monolith, and each new stage can be proven on its own before it joins the chain.

The code has a genuine design flaw, and it is exactly the "wrong specialist" trap from the analogy. The filter grep 'paid$' selects on the text paid at the end of the line, not on the status column, so a row whose status is unpaid also ends in paid and slips through -- it would be counted as a sale. The correct, column-aware test is awk -F, '$3 == "paid"', which checks the third field for exact equality and rejects unpaid. A second, smaller flaw is that sed 's/"//g' deletes every double quote anywhere on the line, so a legitimately quoted amount or a quote inside a field would be mangled; the cleaning step assumes quotes are only decoration around the region. Both flaws come from letting a line-oriented tool make a decision that is really about a specific field.


Common Mistakes

  1. Using grep to make a decision that belongs to a field. grep 'paid$' matches the text at end of line, so unpaid slips through and a region named after a keyword can too. When the decision is really about column three, use awk -F, '$3 == "paid"'.
  1. Reaching for awk (or a loop) to do a plain filter. If you only need the matching lines, grep is shorter, faster, and clearer than an awk program or a while read loop that re-implements matching by hand.
  1. Forgetting sed needs g to replace every match on a line. sed 's/,/;/' changes only the first comma per line; sed 's/,/;/g' changes them all. The missing g is a classic silent half-fix.
  1. Assuming awk's associative-array order is stable. for (r in s) walks the keys in an unspecified order, so grouped output can differ run to run. Pipe it through LC_ALL=C sort when you need a deterministic result.
  1. Not setting awk's field separator. By default awk splits on whitespace, so $2 of a CSV line is the whole thing. Pass -F, (or set FS) for comma-separated data before reading fields.
  1. Editing files in place without care. sed -i rewrites the file and, without a backup suffix, gives you no undo. Redirect to a new file first, or use sed -i.bak so a copy survives while you check the result.
  1. Piping grep into grep when one pattern would do. grep a | grep b can often be a single grep with an extended pattern or grep -E 'a.*b'; chaining is fine for clarity but is not a substitute for understanding the pattern.
  1. Letting an unanchored pattern match too much. grep 'ok' matches ok anywhere, including inside broken or token. Anchor with ^ and $, or match a field boundary, when you mean the whole value.
  1. Treating CSV as if commas never appear inside fields. awk -F, and cut -d, split on every comma, so a quoted field containing a comma breaks the column count. For genuinely complex CSV, use a real CSV parser rather than field-splitting on the delimiter.

Best Practices

  • Pick the specialist that fits the job. Selecting rows is grep, rewriting text is sed, computing over columns is awk; reaching for the right one keeps each command short and obvious.
  • Compose small tools with pipes. Build a result as a chain of one-job stages rather than one dense program, so each stage can be inspected and swapped independently.
  • Anchor patterns to say what you mean. Use ^ and $, or a field test, so a match is the whole value and not an accidental substring.
  • Always set awk's separator for structured data. Pass -F, for CSV or -F'\t' for tab-separated input before you read $2 or $3.
  • Sort grouped awk output for determinism. Follow any for (r in s) summary with LC_ALL=C sort so the order is stable across runs and machines.
  • Prefer a new output file over in-place edits. Redirect sed to a fresh file, or use sed -i.bak, so the original survives until you have checked the change.
  • Test a pipeline stage by stage. Run the first command alone, then add the next, confirming at each step what the following tool will receive.
  • Reach for a real parser when the format is real. grep, sed, and awk are line-and-field tools; for quoted CSV, JSON, or XML, use a parser built for that format instead of bending these three.

Practice Exercises

  1. Rebuild the report with a column-aware filter. Replace the grep 'paid$' in report.sh with awk -F, '$3 == "paid"', add an unpaid row to sales.csv, and show that the new filter excludes it while the old one did not. State in one sentence why the field test is correct.
  1. Three tools, one pipeline. Given a log file where each line is level,component,message, write a single pipeline that keeps only ERROR lines with grep, blanks out the message with sed, and counts errors per component with awk, sorted. Verify the counts by hand against a small sample.
  1. grep flag tour. On any text file, produce four results using grep: the count of matching lines, the non-matching lines, a case-insensitive match, and the matches with line numbers. Note which flag produced each.
  1. Prove the separator matters. Run awk '{ print $2 }' and then awk -F, '{ print $2 }' on orders.csv and explain, in two sentences, why the first prints nothing useful and the second prints the amount.