IntermediateLesson 8 of 15
grep, sed, awk & Co. – Bash
Filter, replace and analyze text – the tools for logs and CSV.
The examples use these two test files (copy the block into the terminal):
cat > server.log <<'EOF'
2024-05-01 10:00:01 INFO Server started
2024-05-01 10:00:05 ERROR Database unreachable
2024-05-01 10:01:10 INFO Request /home 200
2024-05-01 10:02:00 WARN Slow response 1200ms
2024-05-01 10:03:15 ERROR Timeout at /api
2024-05-01 10:04:00 INFO Request /api 200
EOF
cat > daten.csv <<'EOF'
name,stadt,alter
Ada,Berlin,36
Ben,Hamburg,25
Cem,Berlin,41
EOFgrep searches for lines matching a pattern. Important options: -i ignores case, -n line numbers, -v inverts, -c counts, -r recursive, -E extended regex, -o only matches, -w whole word, -A 2/-B 2 context lines.
grep ERROR server.log # both error lines
grep -c ERROR server.log # 2
grep -n -i "request" server.log # with line numbers
grep -v INFO server.log # everything except INFO
grep -E "ERROR|WARN" server.log # regex with alternation
grep -o "[0-9]*ms" server.log # 1200ms
grep -rn "TODO" src/ # recursive in a foldersed is a stream editor, mainly for substitutions s/old/new/ (with g = all matches per line). awk splits lines into fields ($1, $2 …, $NF = last) and calculates – ideal for tables and CSV. cut, sort, uniq, tr cover the rest.
echo "banana" | sed 's/a/X/' # bXnana
echo "banana" | sed 's/a/X/g' # bXnXnX
sed -n '2,3p' server.log # only lines 2 to 3
sed '/INFO/d' server.log # delete INFO lines
awk -F, 'NR > 1 { summe += $3 } END { print "Sum:", summe }' daten.csv # Sum: 102
awk -F, 'NR > 1 { print $1, "lives in", $2 }' daten.csv
awk '$3 == "ERROR" { print $1, $4 }' server.log # date and first word of the message
cut -d, -f2 daten.csv | tail -n +2 | sort | uniq -c # count cities
echo "Hello" | tr 'a-z' 'A-Z' # HELLOWarningPortability:
sed -i (edit a file in place) needs sed -i 's/a/b/' datei on GNU/Linux, but sed -i '' 's/a/b/' datei on macOS/BSD. Write it portably with sed 's/a/b/' datei > tmp && mv tmp datei or use perl -pi -e. date, readlink and grep -P differ in a similar way.TipThe awk structure
CONDITION { ACTION } runs for every line; BEGIN { } before the first, END { } after the last line. awk can replace many one-liners where you would otherwise cobble together cut | sort | uniq.