← All cheatsheets

Shell

Text manipulation — grep, awk, sed cheatsheet

## grep
`grep "pat" file` — basic
`grep -i "pat" file` — case-insensitive
`grep -r "pat" dir` — recursive
`grep -v "pat" file` — invert (lines NOT matching)
`grep -n "pat" file` — show line numbers
`grep -A 3 -B 3 "pat" file` — context lines

## awk
`awk '{print $1}' file` — first column
`awk -F, '{print $2}' file` — CSV, second column
`awk 'NR>1 {sum+=$3} END {print sum}'` — sum column skipping header
`awk '/pat/ {print $0}'` — like grep

## sed
`sed 's/old/new/g' file` — replace all occurrences
`sed -i 's/old/new/g' file` — in-place edit (Linux; `sed -i ''` on macOS)
`sed -n '5,10p' file` — print lines 5-10
`sed '/pat/d' file` — delete lines matching pat
`sed '1d' file` — delete first line