AI Hints
Home›Linux Tutorial›Changing Text
Linux · Lesson 50 of 120

sed: Find and Replace

S/old/new/.

⏱ 2 min read▶ Video at 1:04:06🎓 Free
Watch this lesson in the Linux courseWatch on YouTube ↗Full Linux course

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.

sed: Find and Replace
From the video: sed: Find and Replace
  • 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.

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

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

keyvalue
sed 's/a/b/' filepreview only
/gevery match
sed -ichange the file
Habitpreview, 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
Next up: awk: Working with Columns — print the fields you want