What is sed

sed is a stream editor. It reads input line by line, applies transformations, and writes the result to stdout. The most common use is substituting one string for another, but it can also delete lines, print specific lines, and perform complex text transformations.

Basic substitution

The core syntax is s/pattern/replacement/flags.

Replace the first occurrence of "foo" with "bar" in each line and print to stdout:

sed 's/foo/bar/' file.txt

Replace all occurrences (global flag g):

sed 's/foo/bar/g' file.txt

Edit files in place

By default sed writes to stdout. Use -i to edit the file directly:

sed -i 's/foo/bar/g' file.txt

On macOS, -i requires an argument (use -i '' for no backup):

sed -i '' 's/foo/bar/g' file.txt

Create a backup before editing:

sed -i.bak 's/foo/bar/g' file.txt

This produces file.txt (modified) and file.txt.bak (original).

Case-insensitive substitution

Add the I flag (GNU sed):

sed 's/error/ERROR/gI' file.txt

Delete lines

Delete lines matching a pattern:

sed '/^#/d' file.txt        delete comment lines (starting with #)
sed '/^$/d' file.txt        delete empty lines
sed '5d' file.txt           delete line 5
sed '2,8d' file.txt         delete lines 2 through 8

Print specific lines

Use -n to suppress default output, then p to print only what you want:

sed -n '10,20p' file.txt        print lines 10 to 20
sed -n '/error/p' file.txt      print only lines matching "error"

Multiple expressions

Apply several substitutions in one pass with -e:

sed -e 's/foo/bar/g' -e 's/baz/qux/g' file.txt

Use with pipes

sed works naturally in pipelines:

cat /etc/os-release | sed 's/"//' | grep VERSION
journalctl -n 100 | sed '/^$/d'
grep "ERROR" app.log | sed 's/ERROR/[ERROR]/'

Practical examples

Remove trailing whitespace from all lines:

sed -i 's/[[:space:]]*$//' file.txt

Comment out a line containing a specific string:

sed -i '/ServerName/s/^/#/' /etc/apache2/sites-enabled/000-default.conf

Replace a value in a config file:

sed -i 's/^max_connections = .*/max_connections = 200/' /etc/mysql/my.cnf

Extract lines between two patterns:

sed -n '/START/,/END/p' file.txt

See also

man sed — full reference. For complex multi-line transformations, consider awk or perl -pi -e.

  • Created: December 16, 2007
  • Last edited: July 7, 2026