sed: Find and Replace
S/old/new/.
Imagine a thousand files that mention your old company name, and you need to change them all. Opening each one in an editor would take days. Sed can do it in one command.

- A thousand files to change
- An editor would take days
- sed does it in one command
The replace command
Sed's most famous command looks like this. S, slash, the old text, slash, the new text, slash. S means substitute. Here we replace London with Leeds. Sed prints the changed text, but the file itself isn't changed yet.
sed "s/London/Leeds/" team.csv name,role,city sam,developer,Leeds alex,designer,Paris jo,developer,Berlin priya,manager,Leeds cat team.csv name,role,city sam,developer,London alex,designer,Paris jo,developer,Berlin priya,manager,London
Every match, and saving
By default, sed only replaces the first match on each line. Adding G at the end, for global, replaces every match. And dash I, for in place, saves the changes back into the file. Cat proves the file really changed.
echo "a cat, a cat" | sed "s/cat/dog/g" a dog, a dog sed -i "s/developer/engineer/" team.csv cat team.csv name,role,city sam,engineer,London alex,designer,Paris jo,engineer,Berlin priya,manager,London
Be careful with dash I
Dash I changes files with no undo. Always run sed without dash I first, to preview the result. If it looks right, run it again with dash I. Or make a copy first. That simple habit saves a lot of pain.
| key | value |
|---|---|
| sed 's/a/b/' file | preview only |
| /g | every match |
| sed -i | change the file |
| Habit | preview, then -i |
Summary
Sed replaces text with S slash old slash new. G replaces every match, and dash I saves the file. Preview first. Next, awk, for working with columns.
Key takeaways- s/old/new/
- /g for all
- -i to save