Interview Q&A / Linux & Shell

BeginnerQuick answer1 min readUpdated 3 Oct 2026

How do you replace text in a file using sed?

SHORT ANSWER

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/' f changes the first "cat" on each line.
  • Adding g changes all of them on a line.
  • sed 's/cat/dog/2' f changes only the second.
  • -i writes into the file. -i.bak keeps a copy as f.bak first.
  • 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

bash
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.conf

What 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.

#linux#text-processing#sed

Related questions

Practise more Linux & Shell questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Linux & Shell quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.