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.confDelete by line number:
sed '3d' file.txtDelete a range:
sed '10,20d' file.txtDelete comments:
sed '/^#/d'Delete blank lines:
sed '/^$/d'Delete both comments and blank lines:
sed '/^#/d;/^$/d'Print (p)
Normally, sed prints every processed line automatically.
sed 'p' file.txtEach line is printed twice:
-
Automatic output.
-
pcommand.
Suppress automatic printing:
sed -n 'p' file.txtPrint only matching lines:
sed -n '/ERROR/p' logfile.txtEquivalent to:
grep ERROR logfile.txtInsert (i)
Insert a new line before the current line.
sed '/banana/i\
apple'Result:
apple
bananaAppend (a)
Insert a new line after the current line.
sed '/banana/a\
grape'Result:
banana
grapeChange (c)
Replace the entire addressed line.
sed '/banana/c\
kiwi'Result:
apple
kiwi
oranges 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:
-
Read the line into the Pattern Space.
-
Check whether the address matches.
-
Execute the command(s).
-
Print the result (unless
-nordprevents it). -
Discard the Pattern Space and continue with the next line.
Cheat Sheet
| Command | Meaning |
|---|---|
s | Substitute part of a line |
d | Delete the line |
p | Print the line |
i | Insert before the line |
a | Append after the line |
c | Replace the whole line |
-n | Disable automatic printing |
/pattern/ | Apply command only to matching lines |
1, 5, 10,20, $ | Address by line number, range, or last line |
Key Takeaways
-
sedis 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, andcmodify entire lines, whilesmodifies only matching text within a line. -
Mastering
s,d, addresses, and-ncovers most day-to-daysedusage.