1. 程式人生 > 實用技巧 >9. 第五章 文字處理三劍客之SED

9. 第五章 文字處理三劍客之SED

第五部分 sed

1、刪除centos 7系統/etc/grub2.cfg檔案中所有以空白開頭的行行首的空白字元

[root@centos8 ~]# sed -r 's@^[[:space:]]+(.*)@\1@' 

2、刪除/etc/fstab檔案中所有以#開頭,後邊至少跟一個空白字元的行的行首的#和空白字元

[root@centos8 ~]# sed -n '/^[^#]/p' /etc/fstab 
UUID=baa17659-25ca-488b-9b1e-cd5717e003c4 /                       xfs     defaults        0 0
UUID=83e73d60-7f9a-4c0e-8ebf-4b832f2a0e27 /boot                   ext4    defaults        1 2
UUID=687f9d7a-f30f-4e94-a05e-28505e320c16 /data                   xfs     defaults        0 0

3、在centos 6系統/root/install.log每一行行首增加#號

[root@centos6 ~]# sed -n 's/^/#/p' install.log
[root@centos6 ~]# sed -rn 's/(^.*)/#\1/p' install.log

4、在/etc/fstab檔案中不以#開頭的行的行首增加#號

[root@centos8 ~]# sed -rn 's/(^[^#].*)/#\1/p' /etc/fstab
#UUID=baa17659-25ca-488b-9b1e-cd5717e003c4 /                       xfs     defaults        0 0
#UUID=83e73d60-7f9a-4c0e-8ebf-4b832f2a0e27 /boot                   ext4    defaults        1 2
#UUID=687f9d7a-f30f-4e94-a05e-28505e320c16 /data                   xfs     defaults        0 0
#UUID=bc3b015a-95a4-478a-a865-edca3f3950f4 swap                    swap    defaults        0 0

5、處理/etc/fstab路徑,使用sed命令取出其目錄名和基名

[root@centos8 ~]# echo '/etc/fstab' | sed -r 's@(^/.*./)(.*)@\1@'
/etc/
[root@centos8 ~]# echo '/etc/fstab' | sed -r 's@(^/.*./)(.*)@\2@'
fstab

6、利用sed取出ifconfig命令中本機的IPv4地址

[root@centos8 ~]# ifconfig eth0 |sed -rn '2s@([^0-9]+)([0-9.]+).*@\2@p'
10.0.0.8

7、統計centos安裝光碟中Package目錄下的所有rpm檔案的以.分割倒數第二個欄位的重複次數

[root@centos8 ~]# mount /dev/sr0 /mnt
[root@centos8 ~]# ls /mnt/AppStream/Packages/
[root@centos8 ~]# ls /mnt/AppStream/Packages/ |sed -rn 's/.*\.(.*)\.rpm$/\1/p' |sort| uniq -c
    895 i686
   1953 noarch
   2478 x86_64

8、統計/etc/inin.d/functions文

件中每個單詞的出現次數,並排序(用grep和sed兩種方法分別實現)

[root@centos8 ~]# cat /etc/init.d/functions |sed -r 's@[^[:alpha:]]+@\n@g'|sort |uniq -c|sort -nr |tail -n+2|sort -n
[root@centos8 ~]# grep -Eo "[[:alpha:]]+" /etc/init.d/functions|sort|uniq -c |sort -n

9、將文字檔案的n和n+1行合併為一行,n為奇數行

[root@centos8 ~]# seq 10 |sed 'N;s/\n/ /'
1 2
3 4
5 6
7 8
9 10