Menu
CoddyTech

Editing Text With sed

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 24 of 39.

sed edits text line by line as it passes through. Its most used command is s/old/new/, which replaces the first match on each line and prints the result. The file itself stays as it was.

sed 's/tea/coffee/' menu.txt
sed 's/tea/coffee/g' menu.txt

On the line tea and tea cake, the first command prints coffee and tea cake. The g flag replaces every match on the line, so the second prints coffee and coffee cake. Add -i to write the change back into the file instead of printing it.

sed -i '/^#/d' menu.txt
sed -n '2,4p' menu.txt

/^#/d deletes every line that starts with #, because ^ means the start of a line. -n turns off the automatic printing, and 2,4p prints lines 2 to 4, so the second command shows three lines of the menu.

challenge icon

Challenge

Medium

Write a script that tidies a config file in place.

  1. Open tidy.sh. The config file is its first argument.
  2. With sed -i, delete every line that starts with #. A # later in a line, as in theme=#336699, stays.
  3. With sed -i, replace every localhost with 127.0.0.1, also when a line has it twice.
  4. Print Tidied FILE: with the file name in place of FILE, then the whole file.
  5. Save the file.

Try it: run bash tidy.sh app.conf. It prints:

Tidied app.conf:
host=127.0.0.1
db_url=postgres://127.0.0.1:5432/shop
allowed=127.0.0.1,127.0.0.1:3000
theme=#336699

Run it a second time: the file has no comments and no localhost left, so it prints the same five lines.

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Bash Scripting

Practice on your own: Terminal playground