Text Wrangling: grep, sed, awk and Friends

Search, filter, transform and summarise logs and config files straight from the terminal using composable Unix tools.

Beginner · about 8 hours · difficulty 2/5

Learn first: Linux Command Line and Packages

Logs, config and command output are all text. The classic Unix tools, chained with pipes, let you answer questions like "which IPs caused the most 500 errors in the last hour?" in one line.

The toolkit

  • grep: search with regular expressions. -i, -v, -r, -E, -o, -c, -A/-B for context. ripgrep (rg) is a faster modern alternative.
  • sed: stream editing, mostly substitution: sed -i 's/old/new/g' file. Also delete or print line ranges.
  • awk: field-based processing: awk '{print $1}', -F: for custom separators, sums and counts with associative arrays.
  • cut, sort, uniq -c, tr, wc, xargs, head, tail, column.

A classic pattern

awk '$9 == 500 {print $1}' access.log | sort | uniq -c | sort -rn | head lists the top clients hitting errors.

Regular expressions

Learn anchors (^, $), character classes, quantifiers and groups, and the difference between basic and extended regex.

Pitfalls

Using sed -i without a backup on production config, greedy regex matching more than intended, and xargs breaking on filenames with spaces (use -0 with find -print0).

Good enough to move on: given an unfamiliar log file, you can extract, count and rank any field without opening an editor.

Key concepts

  • grep and ripgrep
  • Regular expressions
  • sed substitutions
  • awk fields and aggregates
  • sort, uniq, cut, tr
  • xargs and find -exec
  • yq for YAML

Mini project

Download a sample nginx access log and write one-liners that report requests per status code, the top 10 IPs, the slowest endpoints, and requests per minute.

Check yourself

How would you replace a hostname in every .conf file under a directory, and how would you make it safe to undo?

Free resources