Blog about Web Programming and Electronics
💬 👤
back Back to blog
Linux

How sed Works

The sed command (Stream EDitor) is one of the oldest and most powerful tools for processing text in the command line. It processes text as a stream — reads one line, modifies it according to commands and prints the result. In this guide we look at the most important commands with practical examples.

sed 's/old/new/g' file.txt

What Is sed

It works as a filter between input and output: it reads line by line, executes commands on each line and prints the result. The original file stays unchanged, unless we use the -i flag.

Replacing Text

The basic command is s, which replaces text by pattern. By default it replaces only the first occurrence in a line, and with the g flag it replaces all occurrences.

echo "hello world" | sed 's/hello/hi/'
# output: hi world

sed 's/old/new/g' file.txt  # replaces all occurrences

Deleting and Inserting Lines

The d command deletes lines, i inserts a line before the specified one, and a adds one after it.

sed '3d' file.txt # deletes line 3
sed '/#/d' file.tx # deletes lines containing #
sed '5i\New line' file.txt # inserts before line 5

Printing Specific Lines

The combination of the -n flag and the p command prints only the lines we need.

sed -n '10,20p' file.txt   # prints lines 10 to 20

Editing Files In Place

With the -i flag sed modifies the file directly. Creating a backup copy with a suffix is highly recommended.

sed -i.bak 's/old/new/g' file.txt
# creates a backup file.txt.bak
back Back to blog