Ninety percent of real-world sed is one command: s/pattern/replacement/flags. The other ten percent is knowing which flags exist, how to point a substitution at the right lines, and how to edit a config file in place without wrecking it. This cheat sheet is thirty substitutions grouped by job, each tested on GNU sed 4.9, with sample input and output where it helps.
If you want to generate one-liners from a plain-English description instead, our guide to writing find, awk and sed one-liners with AI covers that workflow and how to verify the result. This page is the reference you check the output against.
Ground Rules: Quoting, Previews and GNU vs Portable
Use single quotes around sed scripts so the shell leaves $, ! and backslashes alone. Switch to double quotes only when you need a shell variable in the expression. Always preview before you write: drop -i, or diff the result against the original.
# Preview: show what would change, as a diff
$ sed 's/old/new/g' app.conf | diff app.conf -
# Print only the lines a substitution changed (-n suppresses, p prints)
$ sed -n 's/old/new/gp' app.conf
# Then write in place, keeping a backup
$ sed -i.bak 's/old/new/g' app.conf
# Several expressions: chain with ; or repeat -e
$ sed -e 's/foo/bar/g' -e 's/baz/qux/g' file
Every Linux distribution ships GNU sed. macOS and the BSDs ship BSD sed, and Alpine containers ship BusyBox sed, which lack several GNU extensions. The ones used below are marked (GNU); here is what to use when you need portability:
| GNU extension | Example | Portable alternative |
|---|---|---|
| -i without a suffix | sed -i 's/a/b/' f | macOS: sed -i '' 's/a/b/' f, or write to a temp file and mv |
| \+ and \? in basic regex | s/a\+/b/ | sed -E 's/a+/b/' |
| \b \< \> \w \s | s/\bcat\b/dog/ | Bracket classes like [[:alnum:]_] and [[:space:]] |
| I (case-insensitive) flag | s/error/E/I | s/[Ee][Rr][Rr][Oo][Rr]/E/ |
| Ng (Nth onward) flag | s/,/;/2g | Loop with a label, or use awk |
| \U \L \u \l \E case changes | s/.*/\U&/ | tr '[:lower:]' '[:upper:]' or awk toupper() |
| \t \r \xHH escapes | s/\r$// | Embed the character: "s/$(printf '\r')\$//" |
| -z (NUL-separated input) | sed -z 's/\n/,/g' | tr '\n' ',' or the :a;N;$!ba loop |
Basic Substitutions (1β8)
# 1. Replace the first match on each line
$ sed 's/http:/https:/' urls.txt
# 2. Replace every match on each line
$ sed 's/http:/https:/g' urls.txt
# 3. Replace only the 2nd match on each line
$ echo 'a,b,c,d' | sed 's/,/;/2'
a,b;c,d
# 4. Replace the 2nd match and every one after it (GNU)
$ echo 'a,b,c,d' | sed 's/,/;/2g'
a,b;c;d
# 5. Case-insensitive match (GNU)
$ echo 'Error: disk ERROR' | sed 's/error/WARN/Ig'
WARN: disk WARN
# 6. Use another delimiter when the pattern contains slashes
$ sed 's|/usr/local/bin|/opt/app/bin|g' deploy.sh
# 7. Whole words only (GNU): cat, but not concatenate
$ echo 'cat concatenate cat.' | sed 's/\bcat\b/dog/g'
dog concatenate dog.
# 8. & in the replacement is the whole match
$ echo 'port 8080 and 9090' | sed -E 's/[0-9]+/[&]/g'
port [8080] and [9090]
Any character can be the delimiter β the first character after s is the delimiter, so s|a|b|, s#a#b# and s,a,b, all work. Pick one that does not appear in the pattern or replacement instead of escaping every slash.
Regex is greedy β s/".*"/X/ on "a" and "b" replaces everything from the first quote to the last. Use a negated class, s/"[^"]*"/X/, to stop at the first closing quote. Test patterns in the regex tester first.
Capture Groups and Rearranging (9β14)
With -E (extended regex), plain parentheses capture and \1 to \9 refer back to them. Without -E you must write \( and \). Use -E: it is supported by GNU, BSD and BusyBox sed.
# 9. Swap the first two words
$ echo 'hello world' | sed -E 's/^([^ ]+) ([^ ]+)/\2 \1/'
world hello
# 10. Reformat ISO dates as DD/MM/YYYY
$ echo 'due 2026-10-02' | sed -E 's#([0-9]{4})-([0-9]{2})-([0-9]{2})#\3/\2/\1#'
due 02/10/2026
# 11. Keep only the value of KEY=value
$ echo 'DB_HOST=db1.internal' | sed 's/^[^=]*=//'
db1.internal
# 12. snake_case to camelCase (GNU: \U uppercases until \E or end)
$ echo 'max_worker_count' | sed -E 's/_(.)/\U\1/g'
maxWorkerCount
# 13. Wrap every line in quotes and add a comma
$ printf 'web1\nweb2\n' | sed 's/.*/"&",/'
"web1",
"web2",
# 14. Extract a field from matching lines only (-n with the p flag)
$ sed -nE 's/.*user=([^ ]+).*/\1/p' audit.log | sort | uniq -c | sort -rn | head -3
41 deploy
12 backup
3 root
No lazy quantifiers β sed has no .*?. Patterns like [^ ]+ or [^"]* are how you get non-greedy behaviour.
Groups count from the left parenthesis β in ((a)(b)), \1 is ab, \2 is a and \3 is b. Only nine back-references exist.
Whitespace and Line Cleanup (15β21)
# 15. Trim leading whitespace
$ sed 's/^[[:space:]]*//' file
# 16. Trim trailing whitespace, in place with a backup
$ sed -i.bak 's/[[:space:]]*$//' script.sh
# 17. Squeeze runs of spaces and tabs into a single space
$ echo 'a b c' | sed -E 's/[[:space:]]+/ /g'
a b c
# 18. Convert Windows CRLF line endings to LF (GNU)
$ sed -i 's/\r$//' deploy.sh
# 19. Strip comments at the start of a line or after whitespace
$ sed -E 's/(^|[[:space:]])#.*$//' app.conf
# 20. Remove ANSI colour codes from captured output (GNU)
$ sed -E 's/\x1b\[[0-9;]*m//g' build.log > build.txt
# 21. Delete blank and whitespace-only lines
$ sed '/^[[:space:]]*$/d' file
Why bracket classes β [[:space:]] matches spaces, tabs and carriage returns on every sed. \s and \t work in GNU sed but not in BSD sed.
Comment stripping is naive β #19 also eats a # inside a quoted string or a URL fragment. Review the diff before trusting it on anything but simple config files.
The "bad interpreter" error β a script edited on Windows fails with /bin/bash^M: bad interpreter. #18 fixes it; file deploy.sh reports with CRLF line terminators before the fix.
Targeted Substitutions: Addresses and Ranges (22β26)
Put an address in front of s to limit which lines it touches. An address is a line number, a /regex/, a range of either joined with a comma, or $ for the last line. A ! after the address inverts it.
# 22. Only on lines that match a pattern
$ sed '/^[[:space:]]*server_name/s/example\.com/example.org/' site.conf
# 23. On every line that does NOT match (skip comments)
$ sed '/^#/!s/foo/bar/g' app.conf
# 24. Only lines 10-20, or from line 50 to the end
$ sed '10,20s/foo/bar/' file
$ sed '50,$s/foo/bar/' file
# 25. Only inside one INI section: from [database] to the next [header]
$ sed '/^\[database\]/,/^\[/s/^host *=.*/host = db2.internal/' app.ini
# 26. Only the last line: drop a trailing comma
$ printf 'a,\nb,\nc,\n' | sed '$s/,$//'
a,
b,
c
| Address | Selects |
|---|---|
| 5 | Line 5 only |
| 5,10 | Lines 5 through 10 |
| /re/ | Every line matching re |
| /start/,/end/ | From a line matching start through the next line matching end, repeatedly |
| /re/,+3 | A matching line and the 3 after it (GNU) |
| 0~4 | Every 4th line: 4, 8, 12β¦ (GNU first~step) |
| $ | Last line |
| /re/! | Every line NOT matching re |
In-Place Config Edits and Safe Variables (27β30)
# 27. Set a directive whether or not it is commented out
$ sudo sed -i.bak -E 's/^#?[[:space:]]*(PermitRootLogin)[[:space:]].*/\1 no/' /etc/ssh/sshd_config
$ sudo sshd -t && echo syntax ok
# 28. Put a shell variable into the replacement: double quotes, | delimiter
$ new_host=db2.internal
$ sed -i "s|^DB_HOST=.*|DB_HOST=$new_host|" .env
# 29. Comment out one exact line
$ sudo sed -i '/^Listen 80$/s/^/# /' /etc/apache2/ports.conf
# 30. Join all lines with commas
$ sed -z 's/\n/,/g; s/,$/\n/' hosts.txt # GNU: whole file is one record
$ sed ':a;N;$!ba;s/\n/,/g' hosts.txt # classic loop
web1,web2,web3
One-liner #28 breaks as soon as the value contains the delimiter, an & or a backslash, because those are special on the replacement side. Escape the value first:
$ val='p@ss&w/rd'
$ esc=$(printf '%s\n' "$val" | sed 's#[\/&]#\\&#g')
$ echo "$esc"
p@ss\&w\/rd
$ echo 'PASSWORD=old' | sed "s/=.*/=$esc/"
PASSWORD=p@ss&w/rd
-i replaces the file β GNU sed writes a new file and renames it over the old one. Hard links are broken, and a symlink is replaced by a regular file unless you pass --follow-symlinks. Mode and ownership are preserved.
Validate after editing β run the service's own checker before reloading: sshd -t, nginx -t, apachectl configtest, visudo -c. Never edit /etc/sudoers with sed.
Prefer drop-in files when they exist β for sshd, nginx, systemd and sysctl, writing a small file in a .d/ directory is cleaner than patching the vendor file and survives package upgrades. Our Linux tools cheat sheet lists the usual locations.
The classic loop on macOS β BSD sed needs labels on their own line, so write sed -e :a -e N -e '$!ba' -e 's/\n/,/g'.
Idempotence β #27 can run twice safely because it matches the directive in either state. #29 can too, because a commented line no longer matches ^Listen. Write in-place edits so a second run is a no-op; config management tools rely on it.
Frequently Asked Questions
How do I replace all occurrences on a line with sed?
Add the g flag: sed 's/old/new/g' file. Without it, sed replaces only the first match on each line. A number instead of g, such as s/old/new/2, replaces only the Nth match, and GNU sed also accepts 2g to replace the 2nd match and every one after it.
Why does sed -i fail on macOS?
BSD sed on macOS requires a backup suffix argument after -i, so sed -i 's/a/b/' file treats the script as the suffix. Use sed -i '' 's/a/b/' file for no backup, or sed -i.bak which works on both GNU and BSD sed. Alternatively install GNU sed with Homebrew as gsed.
How do I use a shell variable in a sed replacement?
Use double quotes so the shell expands it, and pick a delimiter that cannot appear in the value, for example sed "s|^HOST=.*|HOST=$host|". If the value can contain the delimiter, an ampersand or a backslash, escape those characters first, because they are special in the replacement.
How do I replace newlines with sed?
sed works line by line and strips the newline before applying the script, so s/\n/,/ normally never matches. With GNU sed, use -z so the whole file is read as one record: sed -z 's/\n/,/g'. The portable alternative is the loop sed ':a;N;$!ba;s/\n/,/g', or simply tr '\n' ','.
What is the difference between sed -E and sed -r?
Both enable extended regular expressions, where + ? | ( ) and {} are special without backslashes. -r is the older GNU spelling; -E is what POSIX standardised and what BSD and BusyBox sed accept, so prefer -E in scripts that might run on more than one system.