Skip to content
ohsudo, Home

Module 2: Text and logs

Change text in files with sed

sed edits text without opening an editor, which is what you want in a script, or on the same file on many servers. The habit that keeps you safe: preview first, change the file second.

● Runs 100% in your browser. Nothing here can harm a real system.

Step 1 of 7

Preview a change

sed 's/old/new/' file prints the file with the change. The file itself stays as it was, so this is a safe preview.

Your task

Show app.conf with 8080 replaced by 9090, without changing the file.

guest@ohsudo: ~ — Ubuntu 24.04

Starting the terminal…

What you'll practice

  1. Preview a change. sed 's/old/new/' file prints the file with the change. The file itself stays as it was, so this is a safe preview.
  2. Change the file. -i means "in place": it writes the change to the file, with no confirmation and no undo.
  3. Keep a backup. Add a suffix to -i, as in -i.bak, and sed keeps the original under that name. It's a good habit on a real server.
  4. Every match on a line. By default, sed only changes the first match on each line. g at the end means all of them.
  5. Print some lines. -n turns off normal printing, and p prints what you ask for. It's handy for reading exact lines of a big file, such as the line number in an error message.
  6. Remove comments. d deletes matching lines from the output. ^ means the start of a line, so /^#/d removes comment lines. It's a quick way to see what a long config really sets.
  7. Paths have slashes. A path full of / clashes with the slashes in the command. sed lets you use another separator, such as #, so you don't have to escape each one.

See also