Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

The sed Command in Linux

Search, replace, delete and print text in files and streams with sed.

How-To Guides2 min read8 steps2 screenshots

What sed does

sed (stream editor) changes text as it flows through. It does not need an editor window, so it works well in scripts. You can:

  1. Find patterns in lines and replace them.
  2. Delete lines, characters or words.
  3. Select lines by pattern or line number.
  4. Change case and whitespace, or insert and append text.

Basic use

Show the help:

sed --help
The sed help

Syntax:

sed [options] 'commands' [file-to-edit]
  • options control things like in-place editing (-i) or quiet mode (-n).
  • commands say what sed does to the text.
  • file-to-edit is the file to change.

Replace text

sed 's/oldword/newword/g' test.txt
Replacing a word with sed
  1. s starts a substitution.
  2. /oldword/ is the pattern to find.
  3. /newword/ is the replacement.
  4. g replaces every match in a line. Without g only the first match in each line changes.

By default sed prints the result and does not change the file.

Edit the file in place

sed -i 's/oldword/newword/g' test.txt

Keep a backup copy with a suffix:

sed -i.bak 's/oldword/newword/g' test.txt

Delete lines

Delete line 3:

sed '3d' test.txt

Delete lines 2 to 4:

sed '2,4d' test.txt

Delete lines that contain a word:

sed '/error/d' test.txt

Delete empty lines:

sed '/^$/d' test.txt

Print lines 5 to 10 only:

sed -n '5,10p' test.txt

Print lines that match a pattern:

sed -n '/error/p' test.txt

Insert and append

Add a line before line 2:

sed '2i\This is a new line' test.txt

Add a line after line 2:

sed '2a\This is a new line' test.txt

Change case

sed 's/.*/\U&/' test.txt     # upper case (GNU sed)
sed 's/.*/\L&/' test.txt     # lower case

Use another delimiter

For paths, use | or # instead of /:

sed 's|/old/path|/new/path|g' config.txt

Combine with a pipe

cat test.txt | sed 's/foo/bar/g'

Tips

  • Test without -i first.
  • Use -E for extended regular expressions.
  • On macOS (BSD sed), use sed -i '' ... for in-place editing.

Quick recap

  • sed 's/old/new/g' file replaces text, sed -i saves the change.
  • sed '/pattern/d' deletes lines and sed -n '5,10p' prints lines.