What is sed?

sed (Stream EDitor) is a non-interactive text editor that processes input one line at a time.

It is commonly used for:

  • Text replacement

  • Editing configuration files

  • Log processing

  • Shell scripting

  • CI/CD automation

Unlike Vim, sed edits a text stream automatically without opening an editor.


Basic Syntax

Read from a file:

sed 'command' file.txt

Read from standard input:

command | sed 'command'

Example:

echo "hello world" | sed 's/world/Linux/'

Output:

hello Linux

The Substitute Command

Syntax:

s/old/new/

Meaning:

  • s = substitute

  • old = search pattern

  • new = replacement

Example:

echo "cat dog" | sed 's/cat/lion/'

Output:

lion dog

First Match vs All Matches

Default: replace only the first match on each line.

echo "cat cat cat" | sed 's/cat/dog/'

Output:

dog cat cat

Replace every match:

echo "cat cat cat" | sed 's/cat/dog/g'

Output:

dog dog dog

g = global (all matches on the current line).


Using Another Delimiter

Useful for file paths.

Instead of:

sed 's/\/usr\/bin/\/opt\/bin/'

Use:

sed 's|/usr/bin|/opt/bin|'

Any character can be the delimiter as long as it is used consistently.


Edit a File In Place

Modify the original file:

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

Create a backup first:

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

Result:

file.txt
file.txt.bak

Common Examples

Replace tabs with spaces:

sed 's/\t/    /g'

Remove trailing whitespace:

sed 's/[[:space:]]*$//'

Replace a version number:

sed 's/v1.2/v2.0/'

Template substitution:

VERSION="2.0"
 
sed "s/@VERSION@/$VERSION/g" config.template > config.conf

Key Takeaways

  • sed is a stream editor.

  • The most common command is s/old/new/.

  • By default, only the first match on each line is replaced.

  • Add the g flag to replace all matches.

  • -i edits files directly.

  • Using delimiters such as | makes path substitutions easier to read.