Skip to content

Find and replace in files: sed

IntermediateLesson 22 of 667 min

Replace text in a file with sed s/old/new/g, edit in place with -i, and delete lines with /pattern/d. Practise on a real config file in your browser.

You need to change the same word in a file, maybe in many places, maybe in many files, and opening an editor each time is slow. sed (stream editor) does it from the command line.

Find and replace

The command you'll use most is s/OLD/NEW/. Put it in single quotes so the shell leaves it alone:

sed 's/old-server.lan/new-server.lan/' app/config.ini

Look closely at the last line of the output: only the first match on each line changed. Add g (global) to change every match:

sed 's/old-server.lan/new-server.lan/g' app/config.ini

Changing the file itself

So far sed only printed the result; the file is as it was. That's a good way to check a change first. When it looks right, add -i (in place) and sed rewrites the file:

sed -i 's/old-server.lan/new-server.lan/g' app/config.ini

-i.bak does the same and keeps the original as config.ini.bak.

Careful:Don't write sed ... file > file. The shell empties the file for > before sed reads it, and you are left with nothing. Use -i.

Deleting and printing lines

/PATTERN/d deletes the lines that match. ^ means "at the start of the line", so /^#/d deletes comment lines:

sed '/^#/d' app/config.ini

sed -n '3,5p' prints just lines 3 to 5. The pattern is a regular expression, as in grep, so a . matches any character; write \. when you mean a real dot.

Your turn

The server has moved. In app/config.ini, change every old-server.lan to new-server.lan, set debug = true to debug = false, and delete the two comment lines at the top (they start with #). Change the file itself, not just what sed prints.

Next