Skip to content
Linux Basics: Replacing Text with sed

Linux Basics: Replacing Text with sed

October 8, 2026

sed can change text as it reads a file and write the result to the terminal. Start by previewing a replacement, then save it to a different file when the result looks right.

Use Bash on Debian or Ubuntu. Run these examples in order in the same shell:

practice=$(mktemp -d) && cd "$practice"

Continue only if that command succeeds.

Create a small input file

printf 'red apple\nred red berry\nblue plum\n' > colors.txt

Replace the first red on each line:

sed 's/red/green/' colors.txt
green apple
green red berry
blue plum

The s command means substitute. Its three slashes separate the pattern, replacement, and optional flags. Lines without a match still appear.

Replace every match on a line

sed 's/red/green/g' colors.txt
green apple
green green berry
blue plum

The g flag replaces every non-overlapping match on each line. Neither command above changes colors.txt.

The search pattern is a regular expression, so characters such as . and * have special meanings. In replacement text, & means the entire matched text. These examples use plain words to keep the behavior clear.

Save and check the result

sed 's/red/green/g' colors.txt > updated.txt
cat updated.txt
green apple
green green berry
blue plum

Check that the source still contains its original text:

cat colors.txt
red apple
red red berry
blue plum

Never redirect the result back to the input path with > colors.txt: the shell truncates that file before sed reads it. Keeping a separate output file also gives you a chance to compare the result before replacing anything important.

Clean up

rm -- colors.txt updated.txt
cd / && rmdir -- "$practice"
unset practice

Reference

Debian sed manual

Acknowledgements

This post was created with assistance from AI.

Linux Basics — lesson 22 of 25. Series index

Previous: Quoting Text and Matching Filenames · Next: Filtering and Totaling Fields with awk

Last updated on