流编辑器,主要用来过滤和替换文本内容,增删改查
p(print) -----打印(print) [root@localhost ~]# sed -n '/root/p' /etc/passwd -----匹配打印root的行 root:x:0:0:root:/root:/bin/bash operator:x:11:0:operator:/root:/sbin/nologin s -----替换字符串 g -----全局(global) sed 's/root/ROOT/g' /tmp/passwd|grep "ROOT" -----将root替换为ROOT ROOT:x:0:0:ROOT:/ROOT:/bin/bash operator:x:11:0:operator:/ROOT:/sbin/nologin [root@localhost ~]# seq 10 > a.txt [root@localhost ~]# cat a.txt 1 2 3 4 5 6 7 8 9 10 [root@localhost ~]# sed -n '1,2p' /root/a.txt -----显示第1-2行 1 2 3 4 5 6 7 8 9 10 k s a x z 3 w r s a [root@localhost ~]# sed -n '2,+2p' /root/a.txt -----显示从第二行开始,往下再来2行 k s a x z 3 w r s a 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 打印奇数行(从1开始,2p是加2) [root@localhost ~]# sed -n '1~2p' a.txt 1 3 5 7 9 打印偶数行(从1开始,2p是加2) [root@localhost ~]# sed -n '2~2p' a.txt 2 4 6 8 10 d(delete) -----删除 删除第一行的内容 [root@localhost ~]# sed '1d' a.txt 2 3 4 5 6 7 8 9 10 删除1-3行的内容 [root@localhost ~]# sed '1,3d' a.txt 4 5 6 7 8 9 10 删除空行 sed '/^$/d' a.txt a(append) -----在后面增加 [root@localhost ~]# sed '1a wu' a.txt -----在第1行后增加wu 1 wu 2 3 4 5 6 7 8 9 10 i(insert) -----在前面插入 [root@localhost ~]# sed '3i deng' a.txt -----在第3行前面插入deng 1 2 deng 3 4 5 6 7 8 9 10 ^ -----以....开头 sed 's/^tom/jack/g' /tmp/passwd $ -----以....结尾 sed 's/nologin$/jack/g' /tmp/passwd & -----表示前面匹配到的字符 sed 's/nologin$/&_wudengtian/g' /tmp/passwd -----将nologin结尾的替换为wudengtian c -----整行替换 [root@localhost ~]# sed '/root/chuazai007' /tmp/passwd -----匹配root行替换为huazai007 huazai007 bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin adm:x:3:4:adm:/var/adm:/sbin/nologin lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin sync:x:5:0:sync:/sbin:/bin/sync w(write)-----将模式空间匹配的行,写入到指定文件 sed '/tom/w b.txt' /tmp/passwd -----将tom开头的行写入到b.txt文件中 [root@localhost ~]# cat b.txt -----查看文件 tom:x:1000:1000::/home/tom:/bin/bash tom:x:1000:1000::/home/tom:/bin/bash tom:x:1000:1000::/home/tom:/bin/bash r(read) -----读取 [root@localhost ~]# sed '2r b.txt' /tmp/passwd -----将b.txt添加到/tmp/passwd的第二行 root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/sbin/nologin tom:x:1000:1000::/home/tom:/bin/bash tom:x:1000:1000::/home/tom:/bin/bash tom:x:1000:1000::/home/tom:/bin/bash