文本处理工具sed练习
1、利用sed 取出ifconfig命令中本机的IPv4地址
[root@centos8 ~]# ifconfig ens33 ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 10.0.0.101 netmask 255.255.255.0 broadcast 10.0.0.255 inet6 fe80::20c:29ff:fec0:d588 prefixlen 64 scopeid 0x20<link> ether 00:0c:29:c0:d5:88 txqueuelen 1000 (Ethernet) RX packets 3558 bytes 319499 (312.0 KiB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 8553 bytes 8285509 (7.9 MiB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 [root@centos8 ~]# ifconfig ens33 | sed -nr "2s/[^0-9]+([0-9.]+).*/\1/p" 10.0.0.101
2、删除/etc/fstab文件中所有以#开头,后面至少跟一个空白字符的行的行首的#和空白字符
[root@centos8 ~]# cat /etc/fstab # # /etc/fstab # Created by anaconda on Mon Nov 8 15:06:40 2021 # # Accessible filesystems, by reference, are maintained under '/dev/disk/'. # See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info. # # After editing this file, run 'systemctl daemon-reload' to update systemd # units generated from this file. # UUID=7e52ecef-fcd5-4767-a018-b78c85d5be0e / xfs defaults 0 0 UUID=3c1d9414-9115-43ba-84fb-401472776367 /boot ext4 defaults 1 2 UUID=e97181be-696b-47c9-8c42-5c539598cea4 /data xfs defaults 0 0 UUID=2d32ba3e-4ff7-4df6-bd34-748c877c1bda none swap defaults 0 0 [root@centos8 ~]# sed -i.bak '/^# */d;/^$/d' /etc/fstab [root@centos8 ~]# cat /etc/fstab UUID=7e52ecef-fcd5-4767-a018-b78c85d5be0e / xfs defaults 0 0 UUID=3c1d9414-9115-43ba-84fb-401472776367 /boot ext4 defaults 1 2 UUID=e97181be-696b-47c9-8c42-5c539598cea4 /data xfs defaults 0 0 UUID=2d32ba3e-4ff7-4df6-bd34-748c877c1bda none swap defaults 0 0
3、处理/etc/fstab路径,使用sed命令取出其目录名和基名
[root@centos8 ~]# echo "/etc/fstab" |sed -r 's#(^/.*/)([^/]+/?)#\1#' #取目录名 /etc/ [root@centos8 ~]# echo "/etc/fstab" |sed -r 's#(^/.*/)([^/]+/?)#\2#' #取基名 fstab
浙公网安备 33010602011771号