Text processing: grep, sort, cut and friends
Logs, CSVs, configs and code are all text. A handful of tiny tools let you search, slice and summarise text faster than opening a spreadsheet. Developers and DevOps engineers use these daily to investigate incidents.
grep: search for text
| Flag | Meaning |
|---|---|
-i |
Ignore case |
-n |
Show line numbers |
-c |
Count matching lines |
-v |
Invert: show lines that don't match |
-r |
Search recursively through folders |
-l |
Only list the names of files that match |
-o |
Print only the matching part |
-E |
Extended regular expressions (a|b, +, ?) |
Search a whole project
This finds every TODO in your codebase with its file name and line number. (Modern alternative: ripgrep, rg TODO, which is much faster on big projects.)
Patterns: regular expressions
grep understands regular expressions, a mini-language for text patterns:
| Pattern | Matches |
|---|---|
^text |
A line starting with text |
text$ |
A line ending with text |
. |
Any single character |
[0-9] |
Any digit |
* / + |
Zero or more / one or more of the previous item |
a|b |
a or b (with -E) |
cut: select columns
data/sales.csv has the columns date,region,product,amount:
-d,sets the delimiter (the separator) to a comma.-f2picks field (column) 2, and-f3,4picks fields 3 and 4.
sort and uniq: summarise
That one line answers "How many sales did each region make?" Let's break it down:
cut -d, -f2→ just the region columntail -n +2→ skip the header rowsort→ group identical regions togetheruniq -c→ count each groupsort -rn→ biggest first
Sorting by a column
-t, sets the separator and -k4 sorts by the 4th column. -n makes the sort numeric, so "219" comes after "45".
tr and sed: transform text
trtranslates or deletes characters.sed 's/old/new/g'substitutes text on every line (g= every match on the line, not just the first). It's the classic "find and replace" in pipelines.sed -iedits files in place on real machines.
Real-world investigation
"Payments are failing! Which orders were affected?"
"How many requests did each API endpoint get?"
awk: a mini programming language
On real machines, awk handles column maths that the simpler tools can't:
awk -F, 'NR > 1 { total += $4 } END { print "Revenue:", total }' sales.csv
awk -F, '{ sum[$2] += $4 } END { for (r in sum) print r, sum[r] }' sales.csvPractice
Using data/sales.csv and data/app.log:
- How many sales were for Laptop?
- List the distinct products sold, alphabetically.
- Show every log line that is not INFO, with line numbers.
- Which region had the single biggest sale? (Hint: sort by amount, take the last line, cut the region.)
1.Which command counts the lines in app.log that contain "ERROR"?
2.What does cut -d, -f2 file.csv do?