Linux commands
Browse topics

Editing streams with sed

Version
unversioned
Review
Draft

Summary#

sed normally writes the edited stream to standard output. Use -i to replace the input file with the edited result.

Syntax#

sh
sed 's/old/new/g' file
sed -n '2,4p' file
sed -E -i.bak 's/^(key)=.*/\1=value/' file

Without the g flag, s replaces only the first match on each line. Any character can replace / as the delimiter.

Example#

sh
(
  set -eu
  dir=$(mktemp -d)
  trap 'rm -rf -- "$dir"' EXIT
  cd "$dir"
  printf 'host=localhost\nport=8080\nroot=/var/www\n' > app.conf

  sed -n '2p' app.conf
  sed -n 's|/var/www|/srv/site|p' app.conf
  echo '-- the file is unchanged'
  grep '^root=' app.conf

  sed -E -i.bak 's/^(port)=.*/\1=9090/' app.conf
  echo '-- after the in-place edit'
  grep '^port=' app.conf app.conf.bak
)

Expected output#

Text
port=8080
root=/srv/site
-- the file is unchanged
root=/var/www
-- after the in-place edit
app.conf:port=9090
app.conf.bak:port=8080

Common mistakes#

-i accepts an optional suffix attached to it. sed -iE therefore edits in place and keeps a backup with the suffix E; it does not enable extended regular expressions. Preview the edit without -i first. With -n -i, a script that never prints empties the file.

Version applicability#

This entry describes GNU sed. BSD sed on macOS requires an argument after -i, such as -i '' for no backup, so in-place commands are not portable as written.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0