🎓 A1Learner
🔍
0 of 47 lessons completed

Bash Sed

Sed is a tool that changes text in a stream or a file. Its best known job is swapping one word for another.

A swap that changes nothing on disk

sed prints the line with coffee in place of tea. The cat line proves the file itself still holds the word tea.

echo "I like tea" > drink.txt
sed 's/tea/coffee/' drink.txt
echo "The file still says:"
cat drink.txt

Changing every match on a line

The first command changes only the first tea on the line. Adding g makes the second command change both.

echo "tea and tea" > cups.txt
sed 's/tea/coffee/' cups.txt
sed 's/tea/coffee/g' cups.txt

Saving the change with -i

The -i flag writes the swap into the file. Printing the file afterwards shows coffee, so the edit is saved.

echo "I like tea" > drink.txt
sed -i 's/tea/coffee/' drink.txt
cat drink.txt

Example

echo "the cat sat" > story.txt
echo "the cat ran" >> story.txt
echo "Before:"
cat story.txt
sed -i 's/cat/dog/g' story.txt
echo "After:"
cat story.txt

Key points

  • Write a swap as s/old/new/ inside single quotes.
  • Plain sed prints the changed lines and leaves the file untouched.
  • Without g, sed changes only the first match on each line.
  • Add g at the end to change every match on each line.
  • Use sed -i to write the change back into the file.
  • Check an -i edit with cat to see the new file content.

In this example, the story file holds the word cat on two lines. The first cat prints the original lines for comparison. The sed -i command then swaps every cat for dog inside the file, and the last cat shows the saved result.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the g at the end of 's/tea/coffee/g' do?