Stream editing with sed

sed transforms text on the fly — most often to find and replace.

Syntaxsed 's/pattern/replacement/g' file

sed ("stream editor") edits text as it streams through. Its best-known job is search-and-replace with the s command.

The substitute command

sed 's/old/new/'
  • s — substitute.
  • old — the pattern to find.
  • new — the replacement.
  • Add a trailing g to replace every match on a line, not just the first.

By default sed prints the result and leaves the file untouched. The -i option edits the file in place — powerful, so double-check your pattern first.

Example

Example · bash
# Replace the first 'cat' on each line with 'dog'
sed 's/cat/dog/' pets.txt

# Replace every occurrence on each line
sed 's/cat/dog/g' pets.txt

# Edit the file in place
sed -i 's/localhost/127.0.0.1/g' config.ini

# Delete blank lines
sed '/^$/d' notes.txt

When to use it

  • A DevOps engineer uses 'sed -i "s/localhost/db.internal/g" app.conf' to update a hostname across a config file in-place.
  • A developer strips comment lines from a config template with 'sed "/^#/d" template.conf' before deploying it.
  • A CI script uses sed to inject a build number into a version file: 'sed -i "s/VERSION=.*/VERSION=$BUILD/" version.sh'.

More examples

Substitute text in a file

Shows the substitute command s/old/new/ with the g flag for all occurrences, and -i for in-place editing.

Example · bash
# Replace first occurrence per line (dry run to stdout)
sed 's/http:/https:/' urls.txt

# Replace ALL occurrences per line
sed 's/http:/https:/g' urls.txt

# Edit file in-place
sed -i 's/http:/https:/g' urls.txt

Delete matching lines

Uses the d (delete) command to remove comment lines, blank lines, or a specific line number.

Example · bash
# Delete all comment lines (starting with #)
sed '/^#/d' nginx.conf.template

# Delete blank lines
sed '/^$/d' messy.txt

# Delete a specific line number
sed '5d' file.txt

Insert build version in CI

Demonstrates how CI pipelines use sed -i with a regex anchor to inject dynamic values into config files.

Example · bash
BUILD_NUMBER=142

# Replace the version line with the current build number
sed -i "s/^VERSION=.*/VERSION=${BUILD_NUMBER}/" version.env

grep VERSION version.env
# VERSION=142

Discussion

  • Be the first to comment on this lesson.