✂️
sed cheat sheet
sed edits text line by line. The most common command is s/old/new/. These examples use GNU sed (Linux); on macOS/BSD, use -i '' instead of -i.
Click any command to copy it.
Substitute
| Command | What it does |
|---|---|
sed 's/old/new/' file | Replace the first match on each line. |
sed 's/old/new/g' file | Replace all matches on each line. |
sed 's/old/new/I' file | Case-insensitive replace (GNU). |
sed 's|/usr/local|/opt|g' file | Use another delimiter when the text contains slashes. |
sed -E 's/([a-z]+) ([a-z]+)/\2 \1/' file | Extended regex with groups; swap two words. |
sed 's/foo/[&]/g' file | & stands for the whole match. |
sed -e 's/a/b/' -e 's/c/d/' file | Apply several edits in one pass. |
Print and delete lines
| Command | What it does |
|---|---|
sed -n '5p' file | Print only line 5. |
sed -n '10,20p' file | Print lines 10 to 20. |
sed '1d' file | Delete the first line. |
sed '$d' file | Delete the last line. |
sed '/pattern/d' file | Delete lines matching a pattern. |
sed '/^$/d' file | Delete empty lines. |
sed '/^#/d' file | Delete comment lines. |
sed -n '/start/,/end/p' file | Print the lines between two patterns. |
sed -n '/pattern/p' file | Print only lines matching a pattern (like grep). |
Insert and modify
| Command | What it does |
|---|---|
sed '2i\New line' file | Insert a line before line 2 (GNU). |
sed '/pattern/a\Appended line' file | Append a line after each match (GNU). |
sed 's/^/> /' file | Add a prefix to every line. |
sed 's/$/;/' file | Add a suffix to every line. |
sed 's/[ \t]*$//' file | Remove trailing whitespace. |
sed 'y/abc/xyz/' file | Transliterate characters (a to x, b to y, c to z). |
sed '3s/old/new/' file | Apply a substitution only on line 3. |
Edit files in place
| Command | What it does |
|---|---|
sed -i 's/old/new/g' file | Destructive: Edit the file directly with no undo. Preview first without -i. |
sed -i.bak 's/old/new/g' file | Edit in place and keep a backup named file.bak. |
sed -i 's/old/new/g' *.conf | Destructive: Edit every matching file in place. |
sed -i '/pattern/d' file | Destructive: Delete matching lines from the file permanently. |
sed -i '1i #!/bin/bash' file | Insert a line at the top of the file (GNU). |
Frequently asked questions
Why does sed -i fail on macOS?
BSD sed requires a backup suffix argument. Use sed -i '' 's/a/b/' file, or install GNU sed (gsed).
How do I replace text containing slashes?
Choose a different delimiter, for example sed 's|/old/path|/new/path|g'.