sed Find, replace and edit text in a stream
Reads text line by line, applies editing commands, and prints the result. Most often used to replace one piece of text with another, or to print or delete chosen lines, in a file or in piped output.
Synopsis
sed [OPTION]... 'COMMAND' [FILE]...
sed [OPTION]... -e 'COMMAND' [-f SCRIPTFILE] [FILE]...
Common options
| Option or form | What it does |
|---|---|
-n | Print only what a p command selects. Without it, sed prints every line |
-e command | Add an editing command. Repeat -e to run several commands in order |
-f file | Read the editing commands from a file |
-E, -r | Use extended regular expressions, so ( ), + and | work without backslashes. macOS and GNU both accept -E |
-i extension | Edit the file in place. The extension is a backup suffix. macOS needs it as a separate argument, even an empty one ('') |
-I extension | BSD and macOS only. Like -i, but treats all files as one continuous stream, so line numbers do not restart for each file |
Examples
sed 's/pear/plum/' words.txt
plum
apple
plum
fig
apple
apple
sed -n '2,3p' notes.txt
beta error
gamma
sed '/error/d' notes.txt
alpha
gamma
Beta again
delta
sed '1d' data.csv
ana,red,7
bo,blue,3
cy,red,9
dee,blue,3
sed -E 's/^([^,]*),([^,]*)/\2,\1/' data.csv
team,name,score
red,ana,7
blue,bo,3
red,cy,9
blue,dee,3
sed -i.bak 's/ERROR/FAIL/' app.log
Notes
- In-place editing differs. GNU sed uses -i with no argument, as in sed -i 's/a/b/' file. macOS and BSD sed need an argument after -i, so that form fails there. On macOS: sed -i '' 's/a/b/' file works, and so does sed -i.bak 's/a/b/' file.
- The portable way is sed -i.bak 's/a/b/' file. It works on macOS, BSD and GNU, and leaves file.bak as a backup. Delete the backup afterwards if you do not need it.
- -i changes the file with no undo. Run the command without -i first to check the output, or keep a backup suffix.
- Without the g flag, s/old/new/ replaces only the first match on each line. Add g to replace every match: s/old/new/g. Add I to ignore case: s/old/new/I works on macOS and GNU.
- macOS sed is stricter than GNU sed. Commands such as 1i text on one line fail, and the backslash form \+ did not match on macOS. Use -E with +, and put i, a and c text on a new line after a backslash.
See also
Last reviewed 2026-10-07.