实战:
1、删除/etc/grub.conf文件中行首的空白符;
sed -r ‘[email protected]^[[:spapce:]][email protected]@g‘ /etc/grub.conf
2、替换/etc/inittab文件中"id:3:initdefault:"一行中的数字为5;
sed ‘[email protected]\(id:\)[0-9]\(:initdefault:\)@\15\[email protected]‘ /etc/inittab
3、删除/etc/inittab文件中的空白行;
sed ‘/^[[:space:]]\?$/d‘ /etc/inittab
4、删除/etc/inittab文件中开头的#号;
sed ‘[email protected]^#@@g‘ /etc/inittab
5、删除某文件中开头的#号及后面的空白字符,但要求#号后面必须有空白字符;
sed -r ‘[email protected]^#[[:space:]][email protected]@g‘ /etc/inittab
6、删除某文件中以空白字符后面跟#类的行中的开头的空白字符及#
sed -r ‘[email protected]^[[:space:]]+#@@g‘ /etc/inittab
7、取出一个文件路径的目录名称;
echo "/etc/rc.d/" | sed -r ‘[email protected]^(/.*/)[^/]+/[email protected]\[email protected]‘
案例二:
1、删除/etc/grub2.conf文件中所有以空白开头的行行首的空白字符
sed ‘/^[[:space:]]/d‘ /etc/grub.conf
2、删除/etc/fstab文件中所有以#开头,后面至少跟一个空白字符的行的行首的#和空白字符
sed ‘s/^#[[:space:]]\+//g‘ /etc/grub.conf
3、在/root/install.log每一行行首增加#号
sed ‘s/^\(.*\)/#\1/g‘
4、在/etc/fstab文件中不以#开头的行的行首增加#号
sed ‘s/^[^#].*/#&/g‘ /etc/fstab
5、处理/etc/fstab路径,使用sed命令取出其目录名和基名
#取目录 [[email protected] ~]# echo "/sdf/fdg/" | sed ‘s/^\(\/.*\/\)[^\/]\+\/\?$/\1/g‘ /sdf/ #取基名 [[email protected] ~]# echo "/sdf/fdg/" | sed ‘s/^\(\/.*\/\)\([^\/]\+\)\/\?$/\2/g‘ fdg #取基名 [[email protected] ~]# echo "/et/" | sed ‘s/^\(\/.*\)\<//g‘ et/
#万能方法: #取目录名 [[email protected] ~]# echo "/et.sdf/df/ggsdfd/" | sed ‘s/^\(\/.*\)\<\(.*\)\+\/\?/\2/g‘ ggsdfd/ #取基名 [[email protected] ~]# echo "/et.sdf/df/ggsdfd/" | sed ‘s/^\(\/.*\)\<\(.*\)\+\/\?/\1/g‘ /et.sdf/df/
6、利用sed 取出ifconfig命令中本机的IPv4地址
#简易型: sed -n ‘/inet[^0-9]/p‘ | sed -n ‘s/.*addr:\(.*\)[[:space:]]\+B.*/\1/p‘
#复杂型: [[email protected] ~]# ifconfig | sed -n ‘{/inet[^0-9]/p;}‘ | sed ‘{s/^.*r:\(\<[0-9\.]\+\>\)[[:space:]]\+\(B...t:\(\<[0-9\.]\+\>\)[[:space:]]\+\)\?M..k:\(\<[0-9\.]\+\>\)/\1/g;/^[[:space:]]\?$/d}‘ 192.168.20.133 10.1.249.71 127.0.0.1 #注意:\1 为ip \3 为广播地址 \4 为子网掩码
7、统计centos安装光盘中Package目录下的所有rpm文件的以.分隔倒数第二个字段的重复次数
[[email protected] Packages]# ls ./* | sed -n ‘s/^.*\.\(.*\)\.rpm$/\1/gp‘ | sort | uniq -c 4 i686 919 noarch 2283 x86_64
时间: 2025-01-14 14:35:15