$_ CLI In Depth
Learning progress 0%
lesson text-processing regex awk

Stream Editing with sed

5 min read Module 6: Text Processing: grep, sed & awk Updated Dec 5, 2026
Cheat Sheet
0:00 / 3:20

The model: read, apply, print

sed keeps a pattern space, which holds the current line. For each input line it reads the line into the pattern space, runs every command whose address matches, and then prints the pattern space unless a command suppressed output. Nothing is changed in the file unless you ask for that explicitly. By default sed writes to standard output, so the original file is safe.

Because sed works on a stream, it can sit in the middle of a pipeline. It accepts the same input that grep and cut do, and it produces the same kind of output.

The substitute command

The command s/old/new/ replaces the first match on each line. A trailing g replaces every match on the line. The pattern is a BRE by default, and -E switches to ERE. Inside the replacement, & stands for the whole match, and \1, \2 refer to groups in the pattern.

BASH2 lines
echo 'at cat dog'| sed '/cat/bird/'
echo 'at cat dog'| sed '/cat/bird/g'

The first command prints bird cat dog, because only the first match was replaced. The second prints bird bird dog. Forgetting the g is one of the most common reasons a substitution seems to do nothing on lines that contain more than one match.

Tip

Any character can be the delimiter in an s command. When the text contains slashes, as in a path, write s|/usr/bin|/bin| instead of escaping every slash.

Groups and references

With -E the parentheses form a group, and the replacement refers back to it. This is how you reorder fields. The example swaps a first and last name separated by a space.

BASH1 lines
echo 'da Lovelace'| sed -E '/([A-Za-z]+) ([A-Za-z]+)/\2, \1/'

The output is Lovelace, Ada. The first group is Ada and the second is Lovelace, and the replacement prints them in the reverse order with a comma. In BRE the same pattern would need escaped parentheses.

Addresses: choosing lines

An address in front of a command selects the lines it applies to. A number selects one line, $ selects the last line, and a regular expression between slashes selects the lines that match. Two addresses separated by a comma select a range. The command p prints the pattern space, and -n turns off the automatic printing, so the combination -n with p prints only the selected lines.

BASH3 lines
printf 'lpha\nbeta\ngamma\ndelta\n'> list.txt
sed -n ',3p'list.txt
sed -n 'gam/p'list.txt

The first command prints beta and gamma, the lines two through three. The second prints gamma, the only line that matches the regex.

Deleting and inserting lines

The command d deletes the pattern space and starts the next cycle, so the line is not printed. Combined with an address, it removes lines. A common use is stripping comments and blank lines from a configuration file before reading it.

BASH1 lines
printf ' note\nkey=1\n\nkey=2\n'| sed '^#/d; /^$/d'

The output is key=1 and key=2. The first address deletes lines that start with a hash, and the second deletes empty lines. Multiple commands are separated by a semicolon.

Several commands and the -e option

sed runs every command you give it on each line, in the order given. Commands can be joined with semicolons inside one script, or given one at a time with -e. Both forms produce the same result, and the second is easier to read when the commands are long.

BASH1 lines
printf ' name = old  \n'| sed -e '/^ *//'-e '/ *$//'-e '/ = /=/'

The output is name=old. The first command removes leading spaces, the second removes trailing spaces, and the third tightens the equals sign. The commands see the result of the previous one, so their order matters. Trimming first and then editing the text is the normal way to write such a chain.

A command that matches nothing is not an error. sed quietly passes the line through unchanged, so a typo in a pattern produces output that looks almost right. Compare the input and output with diff, or use sed -n with an explicit p to see exactly which lines were selected, before you rely on a script.

Think of each sed command as a rule with a condition. The address is the condition, and the command is the action. Without an address, the command applies to every line. This makes a scripted edit predictable: you can read a sed script the same way you read the rules of an awk program. When a rule is too broad, narrow its address before you change the command. For example, a substitution that should only touch lines inside a section can use a range such as /^\[server\]/,/^\[/ to restrict the match to that block.

In-place editing, carefully

The option -i writes the result back into the file instead of to standard output. It is convenient and also dangerous, because the original content is replaced. GNU sed accepts -i.bak to keep a backup named with the given suffix. Test the command without -i first, read the output, and only then edit the file. The same advice applies to every tool in this unit.

BASH2 lines
sed '/key/setting/'list.txt > list.new
diff list.txt list.new

This writes the change to a new file and then compares. The comparison shows nothing changed because list.txt has no key on any line. The habit of writing to a new file and diffing is safer than -i while you are learning.

sed and awk, one record at a time

Visualizer

sed edits one line at a time through a buffer. awk splits each record into fields, tests a pattern, runs an action, and can total values in an array.

1 / 5
sed: one input line at a time
input lineafter s/cat/dog/printed

sed reads one input line at a time into a buffer called the pattern space. The commands run in order on that buffer, and at the end of the cycle the buffer is printed unless a command deleted it.

printf 'the cat sat\na cat\ncat cat\n' | sed -e 's/cat/dog/' -e '2d'
Terminal lab · 3 steps · real Linux in your browser

Edit a stream with sed

Print a range, delete lines, and swap fields with sed.

01
Print a range of lines
list.txt has four lines. Print only lines two and three, suppressing the automatic output: ``bash sed -n '2,3p' list.txt > middle.txt ``
Show hint for step 1
-n turns off automatic printing, and the address 2,3 selects the range.
02
Delete comments and blank lines
conf.txt has a comment, a blank line, and two settings. Delete the comment and the blank line: ``bash sed '/^#/d; /^$/d' conf.txt > clean.txt ``
Show hint for step 2
Put two address-and-command pairs in one script, separated by a semicolon.
03
Swap two words with groups
name.txt holds a first and last name. Write the last name first, followed by a comma, using ERE groups: ``bash sed -E 's/([A-Za-z]+) ([A-Za-z]+)/\2, \1/' name.txt > swapped.txt ``
Show hint for step 3
The replacement refers to the first group as \1 and the second as \2.
Check yourself Question 1 of 4
Concept Check Replacing every match recall

Which sed command replaces every occurrence of cat with dog on each line?

Recap & Key Takeaways

sed reads each line into a pattern space, applies commands whose addresses match, and prints the result to standard output.
s/old/new/ replaces the first match on each line, and the g flag replaces all matches; -E enables ERE and \1 refers to groups.
Addresses select lines by number, by $ for the last line, or by a regex, and -n with p prints only selected lines.
Use sed -i only after testing the command, and consider -i.bak to keep a backup.

Primary Sources & Further Reading

Was this lesson helpful? Spot an issue or have a suggestion? Let us know on GitHub.
Report an issue