How do you replace text in a file using sed?
sed 's/old/new/' replaces the first match on each line; add g to replace every match on a line. Add -i to edit the file in place, ideally with a backup suffix like -i.bak, otherwise sed only prints the changed text.
Explain it simply
sed is a stream editor: a find-and-replace that works line by line as text passes through. Think of Ctrl+H in a text editor, but scriptable.
The pattern is s/find/replace/flags.
sed 's/cat/dog/' fchanges the first "cat" on each line.- Adding
gchanges all of them on a line. sed 's/cat/dog/2' fchanges only the second.-iwrites into the file.-i.bakkeeps a copy asf.bakfirst.- Another delimiter helps with paths:
sed 's|/var/www|/srv/www|g' f.
Without -i, sed prints to the screen and the file is untouched, which is a good way to preview. Extra tricks: sed -n '5,10p' prints lines 5 to 10, sed '/^#/d' deletes comment lines and sed '3d' deletes line 3.
Characters like . and * are regex symbols. Escape them with a backslash when you mean them literally.
Example
echo "rate 80, rate 90" | sed 's/rate/price/'
# price 80, rate 90
echo "rate 80, rate 90" | sed 's/rate/price/g'
# price 80, price 90
sed -i.bak 's/localhost/db.internal/' app.confWhat to say in the interview
"sed 's/old/new/g' substitutes on each line, g makes it global per line, and -i edits the file in place. I preview without -i first and use -i.bak to keep a backup. For paths I switch the delimiter to avoid escaping slashes."
Common mistakes
- Using sed -i on a file without a backup or without testing the pattern first.