三剑客之sed
按照行模式处理数据
1查
1.1)打印单行信息
[root@iZbp130bctfwzi3oasr6raZ conf.d]# sed -n '1p' /etc/passwd
root:x:0:0:root:/root:/bin/bash
1.2)打印连续多行信息 1-3 用“,”
[root@iZbp130bctfwzi3oasr6raZ conf.d]# sed -n '1,3p' /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
1.3)打印指定行号信息
[root@iZbp130bctfwzi3oasr6raZ conf.d]# cat -n /etc/passwd|sed -rn "3p;5p"
3 daemon:x:2:2:daemon:/sbin:/sbin/nologin
5 lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
1.4)根据字符串匹配信息
[root@iZbp130bctfwzi3oasr6raZ conf.d]# sed -n '/^root/,/^adm/p' /etc/passwd
root:x:0:0:root:/root:/bin/bash
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
1.5)排除字符串打印
[root@iZbp130bctfwzi3oasr6raZ ~]# sed -n '/^$/!p' test.txt
33
44
55
66
2 增
2.1在指定行插入信息
[root@iZbp130bctfwzi3oasr6raZ conf.d]# cat test.txt
11
22
33
44
55
[root@iZbp130bctfwzi3oasr6raZ conf.d]# sed "1a yangtao" test.txt #在指定行下方插入信息 如果不指定默认每一行
11
yangtao
22
33
44
55
[root@iZbp130bctfwzi3oasr6raZ conf.d]# sed "1i yangtao" test.txt #在指定行上方插入信息 如果不指定默认每一行
yangtao
11
22
33
44
55
[root@iZbp130bctfwzi3oasr6raZ conf.d]# sed '$a yangtao' test.txt #在最后一行添加信息 $a
11
22
33
44
55
yangtao
删
3.1)删除指定行
[root@iZbp130bctfwzi3oasr6raZ conf.d]# sed '1d' test.txt
22
33
44
55
sed -i 修改内容保存至文件
[root@rstx-53 test]# sed -i 's#SELINUX=.*#SELINUX=disabled#g' /etc/selinux/config
[root@rstx-53 test]# cat /etc/selinux/config
# permissive - SELinux prints warnings instead of enforcing.
# disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of three values:
3.2)删除指定信息的行并备份文件
[root@iZbp130bctfwzi3oasr6raZ ~]# cat test.txt
11
22
33
44
55
[root@iZbp130bctfwzi3oasr6raZ ~]# sed -ri.$(date +%F) '/11|22/d' test.txt
[root@iZbp130bctfwzi3oasr6raZ ~]# cat test.txt
33
44
55
[root@iZbp130bctfwzi3oasr6raZ ~]# cat test.txt.2021-06-01
11
22
33
44
55
3.3)sed删除空行信息
[root@iZbp130bctfwzi3oasr6raZ ~]# sed -i '/^$/d' test.txt
[root@iZbp130bctfwzi3oasr6raZ ~]# cat test.txt
33
44
改
4.1) c 指定行替换
[root@iZbp130bctfwzi3oasr6raZ ~]# cat test.txt
33
44
55
66
[root@iZbp130bctfwzi3oasr6raZ ~]# sed '3c 88 ' test.txt
33
44
88
66
sed 's###g' 后项引用前项 s替换 g是指定全局
[root@rstx-53 test]# ifconfig eth0|grep -w inet |sed -r 's#^.*inet (.*) net.*$#\1#g'
192.168.1.53
[root@rstx-53 test]# ifconfig eth0|sed -n -r '2s#^.*inet (.*) net.*$#\1#gp'
192.168.1.53
[root@iZbp130bctfwzi3oasr6raZ test]# ls|sed -r 's#(.*).txt#mv \1.txt \1.jpg#g'|bash
[root@iZbp130bctfwzi3oasr6raZ test]# ls
oldboy10.jpg oldboy1.jpg oldboy2.jpg oldboy3.jpg oldboy4.jpg oldboy5.jpg oldboy6.jpg oldboy7.jpg oldboy8.jpg oldboy9.jpg