sed
sed (stream editor) transforms text line by line. Reach for it for in-place file edits, simple substitutions, and tiny ETL between commands. For multi-line transforms or more than a substitution, reach for awk or a script.
Real sed patterns
EXAMPLE
# 1) Basic substitute (PRINT to stdout — file untouched) sed 's/foo/bar/' file.txt sed 's/foo/bar/g' file.txt # global on each line sed 's/foo/bar/gI' file.txt # case-insensitive # 2) In-place edit sed -i 's/foo/bar/g' file.txt # Linux — overwrites sed -i.bak 's/foo/bar/g' file.txt # save backup sed -i '' 's/foo/bar/g' file.txt # macOS — requires '' argument # 3) Use a different delimiter when the pattern has slashes sed 's|/usr/local|/opt|g' paths.txt # 4) Address — apply only to certain lines sed '2,4 s/foo/bar/g' file.txt # lines 2-4 only sed '/^#/d' file.txt # delete lines starting with # sed '/ERROR/,/END/d' file.txt # delete from ERROR through END sed -n '10,20p' file.txt # print only lines 10-20 # 5) Capture groups + backrefs (ERE flag -E) sed -E 's/^([A-Z]+): (.*)/[\1] \2/' log.txt # INFO: ready → [INFO] ready # 6) Multiple commands sed -e 's/foo/bar/g' -e '/wip/d' file.txt sed -f script.sed file.txt # commands from a file # 7) Insert / append / change whole lines sed '3 i\ NEW LINE' file.txt # insert before line 3 sed '5 a\ APPENDED' file.txt # append after line 5 sed '7 c\ REPLACED' file.txt # replace line 7 # 8) Common one-liners sed -n '$=' file.txt # count lines (= wc -l) sed '/^$/d' file.txt # remove blank lines sed 's/[[:space:]]*$//' file.txt # strip trailing whitespace sed -E 's/<[^>]+>//g' page.html # naive HTML strip sed 'y/abc/ABC/' file.txt # transliterate (like tr) # 9) Pipe-friendly transforms cat config.json | sed -E 's/"version": "[^"]+"/"version": "1.4.0"/' > new.json echo 'hello world' | sed 's/world/Ada/'
Why it matters
For one-line substitutions, sed is unbeatable. For anything multi-line, reach for awk or python — sed’s line-oriented model makes hold-space / branch-label scripts painful to read.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Discussion
Loading…