Ad space (banner)
🖥️Linux Lessons
Lesson 30 / 61

Replacing Text in a File with sed

sed is for when "I want to replace a specific string throughout a file, all at once." sed stands for stream editor, and it reads through a file's content, replacing a given pattern, and prints the result.

Use it in the form sed 's/before/after/' filename. s means substitute, and you specify the target string and the replacement, separated by slashes.

Running sed 's/learn/study/' notes.txt shows the result of replacing the first occurrence of "learn" on each line of notes.txt with "study" (the original file itself isn't changed).

A common early mistake is not realizing only the first match on each line gets replaced — if a line has the target word multiple times, the rest are left untouched. Add g at the end to replace every occurrence.

In real work, this is used constantly inside shell scripts, for automated tasks like bulk-editing config files or reformatting logs.

Linux
Try it (type this into the pseudo terminal)
sed 's/learn/study/' notes.txt

🧑‍💻 You can type this command into the Linux pseudo terminal to try it yourself (this page itself has no interactive terminal).

Ad space (banner)
Ad space (in-article)