Linux Basics: Replacing Text with sed
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.txtReplace the first red on each line:
sed 's/red/green/' colors.txtgreen apple
green red berry
blue plumThe 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.txtgreen apple
green green berry
blue plumThe 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.txtgreen apple
green green berry
blue plumCheck that the source still contains its original text:
cat colors.txtred apple
red red berry
blue plumNever 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 practiceReference
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