正則表達式
grep搜索符合條件的行
man grep
print lines matching a pattern
grep abc需要標準輸入,經常用于管道符的右側
grep?-v不包含pattern的選項
grep?-i忽略大小寫
grep?-n加上匹配模式(pattern)行號
cat?-n /etc/passwd |grep root
ls |grep ks
grep?-c統計有幾行匹配模式只顯示行數
grep?-oi只顯示匹配模式(pattern)本身,忽略大小寫
grep -q 是否有匹配模式都不顯示,可以在$?中顯示
echo?$? 會顯示匹配
grep?-q “root” /etc/psswd =grep “root” /etc/passwd &> /dev/null
grep -nA3?root /etc/passwd顯示字符串的后3行
grep?-nb3 root ??????????????????????????????????????前3行
-nC3 ??????????????????????????????????????????????前后3行
grep -e root -e bash /etc/passwd 包括root 或者?bash
grep root /etc/passwd |grep bash包括root 和?bash
echo?“x2abc3y”|grep?-w abc ?加-w后字符默認為一個單詞
“x2_abc_3y”
“x2-abc-3y”
只識別了“x2-abc-3y”
grep -f file
cat p.txt
root
bash
^c
grep -f p.txt /etc/passwd
可以看到出現了包含root ?bash 字符段的行
Prce(perl Compatible Regular Expressions)
元字符分類:字符匹配?匹配次數?位置錨定?分組
.代表一個字符的任意字符
\.代表.本身??轉義
[]取中括號中的任意一個字符
[^]取除了括號中的任意一個字符
.
.
.
正則表達式
匹配次數
*某一個字符的出現次數
echo axb | grep x* ?????*前面的字符出現的次數是不確定的
.*??代表以前通配符中的* ?任意長度的任意字符串
\?前面一個字符出現了1次或0次
\+前面一個字符出現1次及以上
\{18\}確定18次
\{18,\}18次及以上
\{18,20\}18到20 次
\{,20\}20次以內
[a-z]\+小寫字母至少出現一次
.放在[]中[.]代表任意字符?和通配符一樣
將本機IP地址提取出來Centos7
ifconfig ens33 |grep -o “[0-9.]\{7,\}” |head -n1
ifconfig ens33 |grep -o “[[:digit:]]\{1,3\}\.””[[:digit:]]\{1,3\}\.””[[:digit:]]\{1,3\}\.””[[:digit:]]\{1,3\}” |head -n1
ifconfig ens33 |grep -o “[0-9.]\+” |cut -d” ” -f2
df |grep “dev/sd” |grep -o “[[:digit:]]\{1,3\}”%
正則表達式
位置錨定:定位出現的位置
^表示行首
^root 以root 開頭
$表示行尾
bash$以bash結尾
空行”^$”表示空行
“^[[:space:]]*$”表示空行及TAB及空格行
\<root 代表單詞root 前面沒有字母,可能有冒號
root\>代表單詞root 作為單詞詞尾
\<root\>和?-w ?root一樣
\b也可以表示\<或者\>
正則表達式
分組
\(wang)\
echo?wangwangwang |grep “\(wang\)\{3\}”
后項引用
“\(wang\)\{3\}.*\(wang\)\{3\}”z相當于\(wang\)\{3\}.*\1表達第一個括號中的結果的重復
\2
\3
以左括號(出現的順序來定
\數字匹配的是第一個括號中表示的結果重復
echo rootxxrbbt |grep ‘\(r..t\).*\1’表示沒有結果
echo rootxxroot |grep ‘\(r..t\).*\1’表示正確結果
grep “^\(a\|b\).*” /etc/passwd以a或b 開頭
grep?“a\|bxy”表示a或bxy開頭
grep?“\(a\|b\)xy”表示axy 或bxy開頭
1、顯示/proc/meminfo文件中以大小s開頭的行(要求:使用兩種方法)
grep ^[s\|S] /proc/meminfo
grep ?-i s /proc/meminfo
2、顯示/etc/passwd文件中不以/bin/bash結尾的行
grep -v “/bin/bash$”?/etc/passwd
3、顯示用戶rpc默認的shell程序
cat /etc/passwd |grep “^rpc\b” |cut -d: -f7
4、找出/etc/passwd中的兩位或三位數
grep -o “[0-9]\{2,3\}” /etc/passwd
5、顯示CentOS7的/etc/grub2.cfg文件中,至少以一個空白字符開頭的且后面有非空白字符的行
grep “^[[:space:]]\+.*[^[:space:]]$” /etc/grub2.cfg
6、找出“netstat -tan”命令結果中以LISTEN后跟任意多個空白字符結尾的行
netstat -tan |egrep “LISTEN[[:space:]]*$”
7、顯示CentOS7上所有系統用戶的用戶名和UID
8、添加用戶bash、testbash、basher、sh、nologin(其shell為/sbin/nologin),找出/etc/passwd用戶名和shell同名的行
cat /etc/passwd |grep “^\(.\+\>\):.*\<\1$”
9、利用df和grep,取出磁盤各分區利用率,并從大到小排序
df |grep “/dev/sda”|grep -o “[0-9]\{1,2\}%”|sort -nr
本文來自投稿,不代表Linux運維部落立場,如若轉載,請注明出處:http://www.www58058.com/95515