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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM