Overview

Reach for awk when the task needs fields and for sed when it needs line edits. This card holds the expressions for both, plus the portability traps that bite when a script moves between Linux and macOS. For find, grep, and pipelines that chain all four tools, see find-grep-awk-sed.

awk

awk is a field-oriented language; use it for columnar data.

ExpressionWhat it does
awk '{print $1}' filePrint first field (default delimiter: whitespace).
awk '{print $NF}' filePrint last field.
awk -F: '{print $1}' /etc/passwdSet field delimiter to :.
awk 'NR==5' filePrint line 5.
awk 'NR>=3 && NR<=7' filePrint lines 3 to 7.
awk '/pattern/' filePrint lines matching a regex.
awk '!/pattern/' filePrint lines not matching.
awk '{sum += $2} END {print sum}' fileSum column 2.
awk 'BEGIN {FS=","} {print $1, $3}' file.csvCSV with explicit FS.
awk '{print $2, $1}' fileSwap columns 1 and 2.
awk 'length($0) > 80' fileLines longer than 80 characters.
awk '!seen[$0]++' fileRemove duplicate lines (preserving order).
awk '{gsub(/old/, "new"); print}' fileGlobal substitution in each line.

awk is ideal for log parsing and CSV reshaping when you need field access rather than full regex substitution.

sed

sed edits streams line by line; use it for substitution, deletion, and insertion.

ExpressionWhat it does
sed 's/old/new/' fileReplace first occurrence per line.
sed 's/old/new/g' fileReplace all occurrences per line.
sed -i 's/old/new/g' fileIn-place edit (GNU sed; Linux).
sed -i '' 's/old/new/g' fileIn-place edit (BSD sed; macOS).
sed -i.bak 's/old/new/g' fileIn-place with backup; portable.
sed '/pattern/d' fileDelete lines matching a pattern.
sed -n '/start/,/end/p' filePrint lines between two patterns.
sed -n '10,20p' filePrint lines 10 to 20.
sed '1d' fileDelete the first line (header removal).
sed '$d' fileDelete the last line.
sed 's/^/PREFIX: /' filePrepend to every line.
sed 's/$/ SUFFIX/' fileAppend to every line.
sed '/pattern/a\new line' fileAppend a line after each match (GNU sed).

Common gotchas

  • sed -i is GNU; sed -i '' is BSD. Use sed -i.bak for portable in-place editing; then remove *.bak with find . -name '*.bak' -delete.
  • awk '{print $1}' uses whitespace as the delimiter. A CSV with spaces inside quoted fields will be split incorrectly. Set -F"," and handle quotes explicitly or use a proper CSV tool.
  • sed 's/./X/g' replaces every character; . is a regex metacharacter. Escape it as \. to match a literal dot.