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.

SysOps·37 commands·Last updated 2026-07-21

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/' file
Replace first match per line
sed 's/old/new/g' file
Replace all matches (global)
sed 's/old/new/2' file
Replace the 2nd match per line
sed 's/old/new/I' file
Case-insensitive match
sed -i 's/old/new/g' file
Edit the file in place
sed -i.bak 's/old/new/g' file
Edit and back up the original
sed 's/\/path\/old/path\/new/g' file
Escape slashes when replacing paths
sed 's|old|new|g' file
Use | as delimiter to avoid escaping slashes

Delete 7

sed '5d' file
Delete line 5
sed '5,10d' file
Delete lines 5-10
sed '/pattern/d' file
Delete matching lines
sed '/^$/d' file
Delete blank lines
sed '/^#/d' file
Delete comment lines
sed '$d' file
Delete the last line
sed '1d;$d' file
Delete the first and last lines

Insert & Append 5

sed '5i\new text' file
Insert before line 5
sed '5a\new text' file
Append after line 5
sed '/pattern/i\new text' file
Insert before matching lines
sed '/pattern/a\new text' file
Append after matching lines
sed '5i\line1\nline2' file
Insert multiple lines

Print 5

sed -n '5p' file
Print only line 5
sed -n '5,10p' file
Print only lines 5-10
sed -n '/pattern/p' file
Print only matching lines
sed -n '1p;$p' file
Print first and last lines
sed 's/old/new/p' file
Substitute and print changed lines

Regular Expression 7

sed 's/^prefix/new/' file
Match line start
sed 's/suffix$/new/' file
Match line end
sed 's/\<word\>/new/g' file
Match word boundary
sed 's/[0-9]/X/g' file
Match digits
sed 's/[^0-9]/X/g' file
Match non-digits
sed 's/\(pattern\)/\1/g' file
Capture group and backreference
sed -E 's/(old)/\1-new/g' file
Extended regex (-E or -r)

Multi-line 5

sed ':a;N;$!ba;s/\n//g' file
Delete all newlines
sed 'N;s/\n/ /'
Merge adjacent two lines
sed '/start/,/end/s/old/new/g' file
Substitute within a range
sed '/start/,/end/d' file
Delete lines within a range
sed '/start/,/end/p' file
Print lines within a range

Parameter matrix

ParameterEffectExample
s///Replace the first match on each linesed 's/old/new/' file
/gReplace all matches on the line globallysed 's/old/new/g' file
/2Replace only the 2nd match on each linesed 's/old/new/2' file
/ICase-insensitive matchingsed 's/old/new/I' file
-iIn-place edit (no backup, irreversible)sed -i 's/old/new/g' file
-i.bakIn-place edit that keeps a .bak backupsed -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 Msed '5,10d' file
/pat/dDelete lines matching the patternsed '/^#/d' config
Ni / NaInsert before / append after line Nsed '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 rangesed '/start/,/end/s/old/new/g' file
\( \) and \1Capture group and backreference (BRE)sed 's/\(pattern\)/\1/g' file
-EExtended regex, ( ) needs no escapingsed -E 's/(old)/\1-new/g' file
N;$!ba;s/\n//gDelete all newlines and merge the whole filesed ':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

  1. 1Preview the result before modifying a file

    sed 's/old/new/g' config.yaml

    Without -i it only prints; once confirmed, add -i.bak to write to disk.

  2. 2Edit in place and keep a backup

    sed -i.bak 's/old/new/g' f.txt

    Generates f.txt.bak so you can roll back immediately if something goes wrong.

  3. 3Clean up comments and blank lines

    sed '/^#/d; /^$/d' nginx.conf

    Separate multiple commands with semicolons so it completes in a single scan.

  4. 4Replace only within a specified range

    sed '/start/,/end/s/old/new/g' file

    The range pattern /start/,/end/ can be used for deletion, replacement, and printing.

  5. 5In-place editing on macOS

    sed -i '' 's/old/new/g' file

    BSD -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.yaml

The 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.ini

The 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.txt

N 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