sed Cheatsheet - Linux Text Editing Reference
sed has two pillars: the s/// substitution and the address that decides which lines it applies to, and combining them expresses "change this fragment only inside those lines". The sheet maps onto six recurring tasks — bulk-editing config values, dropping blank or comment lines, inserting before or after a line, printing only matches, writing regular expressions that mean what you intended, and flattening multi-line structures. The thing worth defending against is an unrecoverable mistake: sed -i rewrites the original with no confirmation, so run once without -i, read the output, then commit with -i.bak. The regex group hides a dialect trap — both BSD and GNU sed default to BRE, where +, ? and | must be escaped or you switch with -E. The division of labour is simple: sed rewrites content, awk reshapes structure, grep filters lines; and macOS sed -i demands a backup suffix while Linux accepts a bare -i.
Typical Use Case
For developers who need to rewrite configuration files in bulk. The risk in sed concentrates on irreversibility: -i edits in place with no undo, and the / delimiter collides with paths inside the pattern. This sheet is organised into six groups — substitution, deletion, insertion, printing, regular expressions and multi-line operations. Three pieces of advice matter most: use -i.bak so there is a backup, switch the delimiter to | when the pattern contains slashes, and always preview once without -i before writing to disk.
Substitute 8
sed 's/old/new/' filesed 's/old/new/g' filesed 's/old/new/2' filesed 's/old/new/I' filesed -i 's/old/new/g' filesed -i.bak 's/old/new/g' filesed 's/\/path\/old/path\/new/g' filesed 's|old|new|g' fileDelete 7
sed '5d' filesed '5,10d' filesed '/pattern/d' filesed '/^$/d' filesed '/^#/d' filesed '$d' filesed '1d;$d' fileInsert & Append 5
sed '5i\new text' filesed '5a\new text' filesed '/pattern/i\new text' filesed '/pattern/a\new text' filesed '5i\line1\nline2' filePrint 5
sed -n '5p' filesed -n '5,10p' filesed -n '/pattern/p' filesed -n '1p;$p' filesed 's/old/new/p' fileRegular Expression 7
sed 's/^prefix/new/' filesed 's/suffix$/new/' filesed 's/\<word\>/new/g' filesed 's/[0-9]/X/g' filesed 's/[^0-9]/X/g' filesed 's/\(pattern\)/\1/g' filesed -E 's/(old)/\1-new/g' fileMulti-line 5
sed ':a;N;$!ba;s/\n//g' filesed 'N;s/\n/ /'sed '/start/,/end/s/old/new/g' filesed '/start/,/end/d' filesed '/start/,/end/p' fileParameter matrix
| Parameter | Effect | Example |
|---|---|---|
s/// | Replace the first match on each line | sed 's/old/new/' file |
/g | Replace all matches on the line globally | sed 's/old/new/g' file |
/2 | Replace only the 2nd match on each line | sed 's/old/new/2' file |
/I | Case-insensitive matching | sed 's/old/new/I' file |
-i | In-place edit (no backup, irreversible) | sed -i 's/old/new/g' file |
-i.bak | In-place edit that keeps a .bak backup | sed -i.bak 's/old/new/g' file |
Custom delimiter | | Avoids escaping when the pattern contains / | sed 's|/old/|/new/|g' file |
Nd / 'N,Md' | Delete line N / lines N through M | sed '5,10d' file |
/pat/d | Delete lines matching the pattern | sed '/^#/d' config |
Ni / Na | Insert before / append after line N | sed '5a\new text' file |
-n "Np" | Print only the specified lines (without auto-output) | sed -n '5,10p' file |
/start/,/end/s/// | Replace only within the specified range | sed '/start/,/end/s/old/new/g' file |
\( \) and \1 | Capture group and backreference (BRE) | sed 's/\(pattern\)/\1/g' file |
-E | Extended regex, ( ) needs no escaping | sed -E 's/(old)/\1-new/g' file |
N;$!ba;s/\n//g | Delete all newlines and merge the whole file | sed ':a;N;$!ba;s/\n//g' file |
Common pitfalls
SymptomAfter replacing a string containing a path, sed errors out or the result is empty.
CauseThe / delimiter conflicts with the path in the pattern, requiring a lot of escaping.
FixSwitch to another delimiter: sed "s|/old/path|/new/path|g" file.
SymptomAfter sed -i modifies the file, its contents are entirely empty and cannot be recovered.
CauseThe pattern matched a larger range than expected (e.g. .* greedily matching the whole line), and -i made no backup.
FixUse -i.bak to keep a backup; before executing, run without -i first to inspect the output and confirm.
SymptomYou wanted to replace only the first occurrence per line, but everything got replaced.
CauseThe g flag is in the pattern, or . was treated as a wildcard and matched multiple places.
FixRemove g; for a literal match, escape the . as \. or use grep -F first to confirm the match count.
SymptomOn macOS, sed -i errors out or empties the file.
CauseBSD sed requires a backup suffix after -i; a bare -i is not allowed.
FixOn macOS use sed -i "" "s/old/new/g" file, or sed -i.bak (which auto-generates .bak).
SymptomThe backreference \1 outputs empty or keeps the original text.
CauseUnder BRE, capture groups must be written as \( \) and the replacement uses \1.
FixSwitch to the -E shorthand: sed -E "s/(old)/\1-new/g" file.
SymptomWhen deleting comment lines, body lines containing # were deleted too.
Cause/^#/ matches only lines whose first character is #; writing /#/ deletes every line containing #.
FixUse the anchored form sed "/^#/d"; after confirming, print with -n (without -d) first to inspect the matching range.
SymptomSwitching back and forth between macOS/BSD and GNU gives inconsistent command behavior.
CauseThe -i and -E syntax and some extended options differ between the two.
FixStandardize on -E and -i.bak forms, which work on both platforms; avoid depending on BSD-specific options.
Troubleshooting
1Preview the result before modifying a file
sed 's/old/new/g' config.yamlWithout -i it only prints; once confirmed, add -i.bak to write to disk.
2Edit in place and keep a backup
sed -i.bak 's/old/new/g' f.txtGenerates f.txt.bak so you can roll back immediately if something goes wrong.
3Clean up comments and blank lines
sed '/^#/d; /^$/d' nginx.confSeparate multiple commands with semicolons so it completes in a single scan.
4Replace only within a specified range
sed '/start/,/end/s/old/new/g' fileThe range pattern /start/,/end/ can be used for deletion, replacement, and printing.
5In-place editing on macOS
sed -i '' 's/old/new/g' fileBSD -i requires a suffix; an empty string means no backup, and -i.bak keeps one.
Command Examples
Dry-run a substitution, then edit in place with a backup
sed 's/localhost/0.0.0.0/g' config.yaml
sed -i.bak 's/localhost/0.0.0.0/g' config.yamlThe first line without -i only prints; once confirmed, the second line writes to disk with -i.bak and leaves a .bak. For patterns containing /, switching the delimiter to # is easier.
Output
server: 0.0.0.0 bind: 0.0.0.0:8080 url: http://localhost/api
Substitute within a range of markers
sed '/# BEGIN/,/# END/s/old/new/g' config.iniThe address range /start/,/end/ limits the scope, avoiding accidental changes to same-named content outside the block. To delete a range use sed '/start/,/end/d'.
Output
managed-by-tool
Join adjacent lines
sed -n 'N;s/\n/ /;P;D' data.txtN reads the next line into the pattern space, and s turns the newline into a space. sed multi-line syntax is convoluted; for simple merging of consecutive lines, paste -sd ' ' is more intuitive.
Output
first line second line
Common Pitfalls
- sed -i has no undo and no backup; verify without -i first, then use -i.bak.
- sed defaults to BRE where \+ \| and \( are not special; add -r for extended regular expressions.
- A pattern containing / collides with the delimiter — switch to # or |.
- A range deletion like sed '/start/,/end/d' runs to end of file when the end marker is missing.
- sed is a stream editor, not a logic engine; reach for awk or a script when the transformation is conditional.
Tips
- Before editing in place with sed -i, back up first (-i.bak), or preview without -i.
- sed uses BRE (basic regex) by default; +, ?, | must be escaped or enable ERE with -E.
- On macOS, sed -i requires a backup suffix (e.g. -i ""); on Linux -i works directly.
FAQ
What happens if I omit the g flag in a sed substitution?
Without g, sed replaces only the first match on each line. Given a line with three occurrences of old, sed 's/old/new/' changes just the first and leaves the rest untouched — you must write s/old/new/g to replace them all. That restraint is occasionally useful, for example when you only want to rewrite the first port number in a URL.
How do I operate on a range of lines with sed?
Use Np or a range: sed -n '5,10p' file prints lines 5 through 10, and sed '5,10d' file deletes them. The pattern form sed '/start/,/end/d' file removes everything between the line matching start and the line matching end. Pattern-based ranges are more robust than line numbers for files with irregular structure.
What do the s, d, i and a commands do in sed?
s substitutes matched text in place. d deletes the whole line. i inserts before a matching line, and a appends after it. The key difference is that s keeps the line and changes content, d discards it entirely, and i/a increase the line count. They combine with semicolons: sed '/^#/d; /^$/d' nginx.conf strips comment lines and blank lines in one pass.
Can sed work across lines?
Yes, though the syntax takes a moment. N appends the next line to the pattern space, so N followed by s/\n/ / merges two lines into one; the inverse, sed ':a;N;$!ba;s/\n//g' file, strips every newline and collapses the file to a single line. GNU sed also has -z so N splits on NUL instead of newline, which helps for compressed blobs that contain no newlines.
Why does my sed regex sometimes not take effect?
Most often it is delimiter collision: if the script uses / and your pattern also contains /, as URLs do, you must switch delimiters, e.g. s#https://x#http://y#. Also remember sed defaults to BRE, where \+ \| and \( are not special — write BRE syntax or add -r to switch to extended regular expressions.
Official References
Each command links to its official documentation below, so you can verify the latest usage and read deeper.
Maintained by LaoHand
Publicly updated on Jul 21, 2026, continuously proofread against official docs.
Contact Us
Wrong command or description? Send us corrections, business inquiries or product feedback by email.
Contact Us