正則表達式搭配 sed、awk、tr、cut 這幾把瑞士刀,是日常運維最省力的組合。以下都是可以直接搬進正式環境的寫法。
[root@centos6 ~]# ifconfig | awk -F '[: ]+' 'NR==2{print $4}'
10.1.253.95
[root@centos6 ~]# ifconfig | head -2 | sed -r 's/^.*addr:(.*) Bca.*$/\1/g'
eth1 Link encap:Ethernet HWaddr 00:0C:29:35:DD:AB
10.1.253.95
[root@centos6 ~]# ifconfig | head -2 | tail -1 | tr -s ' ' ':' | cut -d: -f4
10.1.253.95
三種思路:awk 直接指定分隔符取第四欄、sed 用擴展正則把整行替換成捕獲組、tr 先把連續空白壓成單一冒號再用 cut 切片。
[root@centos6 ~]# ifconfig | tr -cs '[:digit:].' '\n' | sort -t. -k4 | tail -8 255.0.0.0 255.255.0.0 255.255.255.0 127.0.0.1 192.168.226.135 10.1.255.255 192.168.226.255 10.1.253.95
tr -cs把非數字非小數點的字元全部擠成換行,只留純數字串,再依第四段排序。
[root@centos6 ~]# df | grep "sd.*" | tr -s ' ' ':' | cut -d: -f1,5 /dev/sda3:4% /dev/sda1:19% /dev/sdb:1% [root@centos6 ~]# df | grep "sd.*" | tr -s ' ' ':' | cut -d: -f1,5 | sort -nr /dev/sda1:19% /dev/sda3:4% /dev/sdb:1%
統計 /etc/init.d/functions 中每個單詞出現的次數,並依頻率由高到低排列:
[root@centos6 ~]# cat /etc/init.d/functions | tr -cs '[:alpha:]' '\n' | sort | uniq -c | sort -nr
83 if
77 then
75 pid
73 echo
72 fi
61 return
57 dev
54 file
50 n
46 local
[root@centos6 ~]# echo "/etc/init.d/functions" | sed -r 's#^(/.*/)[^/]+/?#\1#g' /etc/init.d/ [root@centos6 ~]# echo "/etc/init.d/functions/" | sed -r 's#.*/([^/]+)#\1#g' functions/
這裡刻意用
#當 sed 的分隔符,因為路徑裡滿是斜線,換分隔符能省下一堆跳脫字元。
本文出自「小耳朵」博客,請務必保留此出處 https://purify.blog.51cto.com/10572011/1835797