1. 程式人生 > >正則入坑-2--正則結合awk、sed、grep、find、cut等使用

正則入坑-2--正則結合awk、sed、grep、find、cut等使用

正則表達式 awk sed grep

對文檔中目錄名進行替換
#sed -e ‘s/\/home\/sxzhou/\/home\/SXZHOU/‘ < sed.txt

查找文件格式是txt和jpg格式的文件
#find . ( -name ".txt" -o -name ".jpg" ) -print

遞歸目錄過濾字段
#grep ‘aaaa‘ -R

過濾以大寫字母開頭的行
#grep -n ‘^[A-Z]‘ 1.txt

搜索ooo前沒有g的字符串所在的行
#vi test.txt
sxzhou
sxzhouooo
sxzhogooo
ooosxzhou
SXZHOU

#grep "[^g]ooo" test.txt
sxzhouooo

搜索開頭不是英文字母的行
#vi test.txt
sxzhou
sxzhouooo
sxzhogooo
ooosxzhou
SXZHOU
123ndfkjd

#grep "^[^a-zA-Z]" test.txt
123ndfkjd

過濾空行和註釋行
#egrep -v "^#|^$" 1.txt

過濾包含連續兩個字母o的行
#cat test.txt
sxzhou
sxzhouooo
sxzhogooo
ooosxzhou
SXZHOU
123ndfkjd
dfsdjfoo
hdskfho

#grep -n ‘o{2}‘ test.txt
2:sxzhouooo
3:sxzhogooo
4:ooosxzhou
7:dfsdjfoo

#grep "ooo
" test.txt
sxzhouooo
sxzhogooo
ooosxzhou
dfsdjfoo

搜索包含s和u之間任意個數的任意字符的字符串所在行.表示0個或多個任意字符
#cat test.txt
sxzhou
ooosxzh24~ou!
sxzhsdfkhou++
sxzhsdjfouM
sxzh

#grep "s.
u" test.txt
sxzhou
ooosxzh24~ou!
sxzhsdfkhou++
sxzhsdjfouM

過濾有連續兩個數字或三個數字的行
#grep -n ‘[[:digit:]]{2,3}‘ /etc/passwd

過濾root和apache用戶的shell和UID
#egrep ‘^\b(root|apache)\b‘ /etc/passwd | cut -d: -f3,7

過濾至少一個空白字符開頭的行
#grep "^[[:space:]]+.*" 1.txt

過濾字段的行,字段格式為#開頭、接著至少一個空白字符、接著至少一個非空白字符
#grep "^#[[:space:]]+[^[:space:]]" 1.txt

過濾以root開頭的行
#awk ‘/^root/‘ /etc/passwd

過濾包含500的行,匹配行的第一、二個域加10
#awk -F: ‘/500/ {print $1,$3+10}‘ passwd

正則表示ip地址0.0.0.0到999.999.999.999
"[0-9]{1,3}[.]{3}[0-9]{1,3}"

正則表示IPV4的IP
^(25[0-5]|2[0-4]\d|(1\d{2}|[1-9]?\d))(.(25[0-5]|2[0-4]\d|(1\d{2}|[1-9]?\d)){3}$)
分析:
IP分為四段,每段數字範圍為0-255,IP地址組成特點:250-255、200-249、0-199
250-255 表示 25[0-5]
200-249 表示 2[0-4]\d
0-199 表示
0-9 表示 \d
10-99 表示 [1-9]\d
100-199 表示 1\d{2}

所以0-199可以表示為 (1\d{2}|[1-9]?\d)
0-255就可以表示為 (25[0-5]|2[0-4]\d|(1\d{2}|[1-9]?\d))

從多到少列出每個遠程主機的連接數
#netstat -tnu | grep "[0-9]" | tr -s " " ":" | cut -d: -f6 | sort | uniq -c | sort -rn

持續更新中....

正則入坑-2--正則結合awk、sed、grep、find、cut等使用