Sed
General Information
Stream editor tips and tricks.
Checklist
- Distro(s): Any
- Package: 'sed' package installed
Print Lines
Different ways to print specific lines.
Print only line 5 pattern space
sed -n '5p' /etc/passwd
- -n ⇒ silent; do not print the entire file
Line 5, don't delete it
sed '5!d' /etc/passwd
- !d ⇒ don't delete
Print up to line 5, quit and delete the rest of the output
sed '5q;d' /etc/passwd
- q ⇒ quit/stop processing more input
- d ⇒ delete the pattern space (removes all but line 5 from output)
Swap Patterns
Edit files by swapping pattern spaces.
- Before
cat /etc/resolv.conf # Generated by NetworkManager search local nameserver 208.67.222.222 nameserver 208.67.220.220
- After
sed -i 's/208.67.222.222/8.8.8.8/g' /etc/resolv.conf # Generated by NetworkManager search local nameserver 8.8.8.8 nameserver 208.67.220.220
- -i ⇒ In-line editing
- s ⇒ swap
- g ⇒ global swap (swap every match, not just the first one)
Insert Lines
Insert lines before a found matched pattern.
Given the contents of /etc/resolv.conf:
# Generated by NetworkManager
nameserver 192.168.1.254
Insert a new DNS entry that will be checked first:
sed -i '/nameserver/ i\nameserver 8.8.8.8' /etc/resolv.conf
- /nameserver/ ⇒ pattern to match
- -i ⇒ in-line editing (changes the file in place)
- i\ ⇒ insert
Results in:
# Generated by NetworkManager
nameserver 8.8.8.8
nameserver 192.168.1.254
Insert at first line
Insert also works against line numbers.
Insert a new comment at line 1:
sed -i '1 i\# My first line comment' /etc/resolv.conf
Results in:
# My first line comment # Generated by NetworkManager nameserver 8.8.8.8 nameserver 192.168.1.254
Append Lines
Append lines after a found matched pattern.
Given the contents of /etc/resolv.conf:
# Generated by NetworkManager
nameserver 8.8.8.8
nameserver 192.168.1.254
Append a new DNS entry that will be checked 2nd:
sed -i '/nameserver 8.8.8.8/ a\nameserver 8.8.4.4' /etc/resolv.conf
Results in:
# Generated by NetworkManager
nameserver 8.8.8.8
nameserver 8.8.4.4
nameserver 192.168.1.254
Remove Lines
Remove lines that match a pattern.
Given /etc/resolv.conf:
# Generated by NetworkManager
nameserver 8.8.8.8
nameserver 8.8.4.4
nameserver 192.168.1.254
Remove the 8.8.4.4 entry:
sed -i '/8.8.4.4/d' /etc/resolv.conf
Results in:
# Generated by NetworkManager
nameserver 8.8.8.8
nameserver 192.168.1.254