Overview

sed processes one line at a time. These editing commands modify or control the current Pattern Space.


Delete (d)

Delete the current line.

sed '/debug/d' config.conf

Delete by line number:

sed '3d' file.txt

Delete a range:

sed '10,20d' file.txt

Delete comments:

sed '/^#/d'

Delete blank lines:

sed '/^$/d'

Delete both comments and blank lines:

sed '/^#/d;/^$/d'

Normally, sed prints every processed line automatically.

sed 'p' file.txt

Each line is printed twice:

  1. Automatic output.

  2. p command.

Suppress automatic printing:

sed -n 'p' file.txt

Print only matching lines:

sed -n '/ERROR/p' logfile.txt

Equivalent to:

grep ERROR logfile.txt

Insert (i)

Insert a new line before the current line.

sed '/banana/i\
apple'

Result:

apple
banana

Append (a)

Insert a new line after the current line.

sed '/banana/a\
grape'

Result:

banana
grape

Change (c)

Replace the entire addressed line.

sed '/banana/c\
kiwi'

Result:

apple
kiwi
orange

s vs c

Substitute only part of a line:

sed 's/old/new/'

Replace the whole line:

sed '/pattern/c\
new line'

Use s for partial replacements and c when the entire line should be replaced.


Combining Commands

Commands execute sequentially.

sed '
/debug/d
/server/a\
timeout=30
'

or

sed -e '/debug/d' \
    -e '/server/a\
timeout=30'

Common Sysadmin Examples

Remove comments:

sed '/^#/d'

Remove blank lines:

sed '/^$/d'

Keep only active configuration:

sed '/^#/d;/^$/d'

Insert a header at the beginning of a file:

sed '1i\
# Generated automatically'

Replace a configuration value:

sed 's/^Listen .*/Listen 8080/'

Replace an entire configuration line:

sed '/^Listen/c\
Listen 8080'

Mental Model

For every input line:

  1. Read the line into the Pattern Space.

  2. Check whether the address matches.

  3. Execute the command(s).

  4. Print the result (unless -n or d prevents it).

  5. Discard the Pattern Space and continue with the next line.


Cheat Sheet

CommandMeaning
sSubstitute part of a line
dDelete the line
pPrint the line
iInsert before the line
aAppend after the line
cReplace the whole line
-nDisable automatic printing
/pattern/Apply command only to matching lines
1, 5, 10,20, $Address by line number, range, or last line

Key Takeaways

  • sed is a stream editor that processes one line at a time.

  • Addresses determine where a command runs.

  • Commands determine what happens to the current line.

  • d, i, a, and c modify entire lines, while s modifies only matching text within a line.

  • Mastering s, d, addresses, and -n covers most day-to-day sed usage.