1. 程式人生 > >Linux中正則表達式的練習集合

Linux中正則表達式的練習集合

LINUX 正則表達式 grep

1、找出ifconfig “網卡名” 命令結果中本機的IPv4地址
ifconfig | head -n 2 |tail -1 |tr -s " " |cut -d" " -f3
技術分享圖片
2、查出分區空間使用率的最大百分比值
df |tr -s " " |cut -d" " -f5
技術分享圖片
3、查出用戶UID最大值的用戶名、UID及shell類型
cat /etc/passwd | cut -d: -f1,3,7| sort -nt: -k2 |tail -n 1
技術分享圖片
4、查出/tmp的權限,以數字方式顯示
stat /tmp | head -n 4 |tail -n 1|cut -c10-13
技術分享圖片
5、統計當前連接本機的每個遠程主機IP的連接數,並按從大到小排序(無圖)
cat /var/log/httpd/access_log |cut -d" " -f1 |sort |uniq -c |sort -n -r |head
6、顯示CentOS7的/etc/grub2.cfg文件中,至少以一個空白字符開頭的且後面存非空白字符的行
grep "^[[:blank:]]+" /etc/grub2.cfg |grep -v "^[[:space:]]$"
技術分享圖片
7、找出“netstat -tan”命令的結果中以‘LISTEN’後跟任意多個空白字符結尾的行
netstat -tan |grep "LISTEN[[:blank:]]
$"
技術分享圖片
8、顯示CentOS7上所有系統用戶的用戶名和UID
cat /etc/passwd |cut -d: -f1,3 | egrep -v "[0-9]{4,}"
技術分享圖片
9、添加用戶bash、testbash、basher、sh、nologin(其shell為/sbin/nologin),找出/etc/passwd用戶名同shell名的行
grep "(^.)\>.\<\1$" /etc/passwd
技術分享圖片
10、利用df和grep,取出磁盤各分區利用率,並從大到小排序
df |egrep "\<[0-9]%." -o|sort -nr
技術分享圖片
11、顯示三個用戶root、mage、wang的UID和默認shell(C7代替)
cat /etc/passwd |egrep "^(root|C7)" |cut -d: -f1,3
技術分享圖片
12、找出/etc/rc.d/init.d/functions文件中行首為某單詞(包括下劃線)後面跟一個小括號的行
egrep ".()" /etc/rc.d/init.d/functions
技術分享圖片
13、使用egrep取出/etc/rc.d/init.d/functions中其基名(弄得有點投機嫌疑)
echo /etc/rc.d/init.d/functions | egrep "[a-z]
$"
技術分享圖片
14、使用egrep取出上面路徑的目錄名
echo /etc/rc.d/init.d/functions | egrep "/.*/"
技術分享圖片
15、統計last命令中以root登錄的每個主機IP地址登錄次數
last|cut -c23-38 |sort|uniq -c|sort -rn|head -n 1
技術分享圖片
16、利用擴展正則表達式分別表示0-9、10-99、100-199、200-249、250-255
echo {1..255} |
egrep "\<[0-9]\>"
技術分享圖片
egrep "\<1[0-9]\>"
技術分享圖片
egrep "\<1[0-9][0-9]\>"
技術分享圖片
egrep "\<2[0-4][0-9]\>"
技術分享圖片
egrep "\<25[0-5]\>"
技術分享圖片
17、顯示ifconfig命令結果中所有IPv4地址(瞎寫)
ifconfig |egrep "[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}"
技術分享圖片
18、將此字符串:welcome to tiantianpaokuzhentmdehaowan linux 中的每個字符去重並排序,重復次數多的排到前面
echo wecomele to tiantianpaokuzhentmdehaowan linux |grep -o . |sort |uniq -c |sort -nr
技術分享圖片
如有錯誤之處還請批評指正。

Linux中正則表達式的練習集合