[root@localhost shell]# sed -n '1p' zxc1 ##打印第一行
one
[root@localhost shell]# sed -n '$p' zxc1 ##打印最后一行
twelve
[root@localhost shell]# sed -n '1,3p' zxc1 ##打印输出第一行至第三行的内容,可在3前面加一个+符号
one
two
three
[root@localhost shell]# sed -n '3,$p' zxc1 ##打印从第三行至最后一行的内容
three
four
five
six
seven
eight
nine
ten
eleven
twelve
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[root@localhost shell]# sed 5q zxc1 ##q用法:打印前5行内容后退出
one
two
three
four
five
1
2
3
4
5
6
1
2
3
4
5
6
sed -n 'p;n' zxc1
sed -n 'n;p' zxc1
1
2
3
1
2
3
sed -n '2,${n;p}' zxc1
1
1
sed -n '/user/p' /etc/passwd
1
1
sed -n '/^a/p' /etc/passwd
1
1
sed -n '/bash$/p' /etc/passwd
sed -n '/ftp\|root/p' /etc/passwd
1
2
3
1
2
3
sed -n '2,/nobody/p' /etc/passwd
sed -n '2,/nobody/=' /etc/passwd
1
2
3
1
2
3
sed -n '2,/nobody/=;2,/nobody/p' /etc/passwd
1
1
[root@localhost shell]# sed -nr '/ro{1,}t/p' /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
##-r表示支持正则表达式##匹配一次以上的o,就能匹配到root
1
2
3
4
5
1
2
3
4
5
删除行
sed'd' zxc1
sed'3d' zxc1
sed'2,4d' zxc1
1
2
3
4
5
1
2
3
4
5
[root@localhost shell]# sed '/^$/d' zxc1##用作删除空行
1
2
1
2
[root@localhost shell]# sed '/nologin$/d' /etc/passwd##删除以nologin为结尾的内容[root@localhost shell]# sed '/nologin$/!d' /etc/passwd##"!"表示取反操作
1
2
3
4
5
1
2
3
4
5
sed -n 'p' zxc2
sed'/2/,/3/d' zxc2
1
2
3
1
2
3
cat zxc2
sed'/10/,/3/d' zxc2
1
2
3
1
2
3
替换标记
##格式:
行范围 s/旧字符串/新字符串/替换标记
1
2
1
2
4种替换标记:
数字:表明新字符串将替换第几处匹配的地方
g:表明新字符串将会替换所有匹配的地方
p:打印与替换命令匹配的行,与-n一起使用
w 文件:将替换的结果写到文件中
示例:
sed -n 's/root/admin/p' /etc/passwd
sed -n 's/root/admin/2p' /etc/passwd
1
2
3
1
2
3
sed -n 's/root/admin/gp' /etc/passwd
1
1
sed -n 's/root//gp' /etc/passwd
1
1
[root@localhost shell]# sed '1,20 s/^/#/' /etc/passwd