appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Text processing: grep, sed, awk and sort

Lesson 2 of 412 minIntermediate

Filter, transform and summarise text and logs with a few small tools.

Linux tools do one thing well and connect with pipes. Learning four of them lets you answer most questions about a log or a CSV file.

grep: find lines

grep -i error app.log          # ignore case
grep -rn "TODO" src/           # recursive, with line numbers
grep -E "ERROR|WARN" app.log   # extended regex
grep -v debug app.log          # invert: lines without it

sed: edit a stream

sed 's/http:/https:/g' links.txt     # replace on every line
sed -n '10,20p' file.txt             # print only lines 10 to 20
sed -i.bak 's/old/new/' config.ini   # edit in place, keep a backup

awk: work with columns

awk '{print $1}' access.log                 # first column
awk -F, '$3 > 100 {print $1, $3}' data.csv  # CSV, filter on column 3
awk '{sum += $2} END {print sum}' sales.txt # total of column 2

sort and uniq: count things

awk '{print $1}' access.log | sort | uniq -c | sort -nr | head

That one line lists the ten most frequent values of the first column. uniq only collapses neighbouring duplicates, so always sort first.

CarefulTest sed -i on a copy or with a backup suffix first. It rewrites the file and there is no undo.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. Why sort before uniq?
2. What does grep -v do?
Hintawk '{print $1}' file

Key terms