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.txt
Replaces the first cat on each line with dog.
sed "s/cat/dog/g" pets.txt
Replaces every cat on each line. The g stands for global.
sed "s/cat/dog/gI" pets.txt
Replaces every cat, ignoring case.
sed "s/\bcat\b/dog/g" pets.txt
Plain 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.conf
Uses # 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.conf
Changes 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.txt
Prints only lines 2 to 4.
sed "1d" names.csv
Removes the first line, such as the heading row of a CSV file.
sed "/^#/d" config.conf
Removes comment lines that start with #.
sed -e "/^#/d" -e "/^$/d" config.conf
Removes comment lines and blank lines, leaving just the settings.

Adding lines and rearranging text

sed "1i Name,City,Amount" data.csv
Inserts a new first line.
sed "$ a # End of file" config.conf
Adds 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

OptionMeaning
s/old/new/Replace the first match on each line
s/old/new/gReplace every match
-iEdit the file in place
-i.bakEdit in place and keep a backup
-n "5p"Print only line 5
"3d"Delete line 3
"/text/d"Delete lines containing text
-EExtended patterns