Find and replace in files: sed
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.iniLook 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.iniChanging 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.inised -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.
Your task
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.
- Every old-server.lan is now new-server.lan (not done yet)
- debug = false (not done yet)
- No comment lines left, the rest untouched (not done yet)
The checklist ticks itself off as you work in the terminal: any way that gets the result counts.
Hints come one at a time, then one way to do it. Try each before the next.
What this lesson uses, in one place.
sed 's/old/new/g'- Replace every old with new on each line (without g, only the first) More on sed
sed -i- Edit the file itself instead of printing the result More on sed
sed '/x/d'- Delete the lines that match x More on sed
Every everyday command on one page: the Linux commands cheat sheet.