1.删除centos7系统/etc/grub2.cfg文件中所有以空白开头的行行首的空白字符。
首先,先查看该/etc/grub2.cfg文件中存在多少的空白行!
[root@server02 ~]# cat grub2.cfg | grep -c "^$"
17
接着,
[root@server02 ~]#sed -i.bak "/^$/d" grub2.cfg
再查看是否存在空白行
[root@server02 ~]#cat grub2.cfg | grep -c "^$"
0
2.删除/etc/fstab文件中所有以#开头,后面至少跟一个空白字符的行的行首的#和空白字符。
代码:
[root@server02 ~]#cat fstab | sed -n '/^#[[:space:]]/s/^#[[:space:]]//p'
结果:
/etc/fstab
Created by anaconda on Fri Jun 28 21:29:20 2024
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
3. 在centos6系统/root/install.log每一行行首增加#号
代码:
[root@localhost ~]# sed -ri.bak '/^./s/(^.)/#\1/' install.log
结果:
#Installing ql2200-firmware-2.02.08-3.1.el6.noarch
#Installing rt73usb-firmware-1.8-7.el6.noarch
#Installing ipw2100-firmware-1.3-11.el6.noarch
#Installing ql23xx-firmware-3.03.27-3.1.el6.noarch
#Installing ipw2200-firmware-3.1-4.el6.noarch
#Installing rootfiles-8.1-6.1.el6.noarch
#*** FINISHED INSTALLING PACKAGES ***
4.在/etc/fstab文件中不以#开头的行的行首增加#号
代码:
[root@server02 ~]# sed -nr "s/^([^#])/#\1/p" fstab
结果:
#/dev/mapper/centos-root / xfs defaults 0 0
#UUID=3b1f5650-c38c-477e-9092-532de6c71268 /boot xfs defaults 0 0
#/dev/mapper/centos-swap swap swap defaults 0 0
5.处理/etc/fstab路径,使用sed命令取出其目录名和基名
①.取目录名:
代码:
[root@server02 ~]#echo "/etc/fstab" | sed -nr "s#(/.*/)([^/]+/?)#\1#p"
结果:
[root@server02 ~]#echo "/etc/fstab" | sed -nr "s#(/.*/)([^/]+/?)#\1#p"
/etc/
②.取基名:
代码:
[root@server02 ~]#echo "/etc/fstab" | sed -nr "s#(/.*/)([^/]+/?)#\2#p"
结果:
[root@server02 ~]#echo "/etc/fstab" | sed -nr "s#(/.*/)([^/]+/?)#\2#p"
fstab
6、利用sed 取出ifconfig命令中本机的IPv4地址
代码:
[root@server02 ~]#ifconfig | sed -nr '2s/^[^0-9]+([0-9.]+) .*/\1/p'
结果:
[root@server02 ~]#ifconfig | sed -nr '2s/^[^0-9]+([0-9.]+) .*/\1/p'
10.1.1.2
7.统计centos安装光盘中Package目录下的所有rpm文件的以,分隔倒数第二个字段的重复次数
代码:
[root@server02 Packages]#ls *.rpm | sed -nr 's#.*\.(.*)\.rpm#\1#p' | sort | uniq -c
结果:
1405 noarch
2665 x86_64
8、统计/etc/init.d/functions文件中每个单词的出现次数,并排序(用grep和sed两种方法分别实现)
①grep
代码:
[root@server02 ~]#cat functions | grep -E "[[:alpha:]]" | tr "[[:punct:]][[:digit:]]" " " |tr -s " " "\n" | grep -Ev "^$"|sort | uniq -c
结果:
13 var
6 verbose
4 via
5 warning
5 WARNING
1 We
1 where
1 whether
3 while
1 width
1 will
2 with
14 x
1 xcondrestart
1 xforce
1 xreload
1 xrestart
1 xstart
1 xstop
1 xtry
3 yes
2 yY
28 z
②.sed
代码:
[root@server02 ~]#cat functions | tr "[[:punct:]][[:digit:]]" " " |tr " " "\n" | sed -nr "/[[:alpha:]]/p" | sort |uniq -c
[root@server02 ~]#cat functions | tr "[[:punct:]][[:digit:]] " "\n" |sed -nr "/[[:alpha:]]/p" | sort | uniq -c
结果:
13 var
6 verbose
4 via
5 warning
5 WARNING
1 We
1 where
1 whether
3 while
1 width
1 will
2 with
14 x
1 xcondrestart
1 xforce
1 xreload
1 xrestart
1 xstart
1 xstop
1 xtry
3 yes
2 yY
28 z
9.将文本文件的n和n+1行合并为一行,n为奇数行
代码:
[root@server02 ~]# cat expression | sed -n "N;s/\n/ /;p"
结果:
安慰 焦急
敬慕 惭愧
敬畏 嫉妒
心疼 紧张
着急 心得
文章续写到此,欢迎大家品读,多多支持!!