Shell Replacing Text with Sed
sed replaces text in a stream of lines. The s command swaps one piece of text for another.
Replace one word
sed swaps milk for bread in the line.
echo "Buy milk" | sed s/milk/bread/The file stays the same
sed prints the changed lines, then cat shows the file is unchanged.
sed s/milk/tea/ notes.txt
cat notes.txtReplace in a stream
cat feeds the shopping lines into sed, and sed swaps apples for pears.
cat shopping.txt | sed s/apples/pears/Example
sed s/milk/bread/ notes.txt > newnotes.txt
cat newnotes.txtKey points
- Use sed s/old/new/ to replace text.
- sed shows the changed lines, and the file stays the same.
- A stream: lines that flow from one command to the next.
- Use a pipe to feed lines into sed from another command.
In this example, sed swaps milk for bread in notes.txt. The changed lines go into newnotes.txt. Then cat prints the new file.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What happens to the file when sed prints a replacement?