Linux sed Command: Find and Replace Text
sed is a stream editor. It reads text line by line and changes it as it goes. It is most often used to find and replace text, or to delete lines, without opening the file in an editor.
Find and replace
By default sed prints the result to the screen and leaves the file unchanged, so you can check it first.
sed "s/cat/dog/" pets.txtReplaces the first cat on each line with dog.
sed "s/cat/dog/g" pets.txtReplaces every cat on each line. The g stands for global.
sed "s/cat/dog/gI" pets.txtReplaces every cat, ignoring case.
sed "s/\bcat\b/dog/g" pets.txtPlain patterns also match inside other words, so category would become dogegory. \b marks the edge of a word, so this only changes cat on its own.
sed "s#/var/www#/srv/www#g" site.confUses # instead of / to separate the parts, which is easier to read when the text contains slashes.
Editing a file
sed -i.bak "s/old.example.com/new.example.com/g" site.confChanges the file itself (-i) and keeps the original as site.conf.bak.
Test before you use -i. Run the command without -i first to see the result. Using -i on its own changes the file with no backup.
Showing and deleting lines
sed -n "2,4p" pets.txtPrints only lines 2 to 4.
sed "1d" names.csvRemoves the first line, such as the heading row of a CSV file.
sed "/^#/d" config.confRemoves comment lines that start with #.
sed -e "/^#/d" -e "/^$/d" config.confRemoves comment lines and blank lines, leaving just the settings.
Adding lines and rearranging text
sed "1i Name,City,Amount" data.csvInserts a new first line.
sed "$ a # End of file" config.confAdds a line at the end.
sed -E "s#([0-9]{4})-([0-9]{2})-([0-9]{2})#\3/\2/\1#g" dates.txt
Changes dates like 2026-11-02 to 02/11/2026. The brackets capture each part, and \1 \2 \3 put them back in a new order.
Quick reference
| Option | Meaning |
|---|---|
s/old/new/ | Replace the first match on each line |
s/old/new/g | Replace every match |
-i | Edit the file in place |
-i.bak | Edit in place and keep a backup |
-n "5p" | Print only line 5 |
"3d" | Delete line 3 |
"/text/d" | Delete lines containing text |
-E | Extended patterns |