grep學習示例
Linux中grep命令使用較多,現將自己學習的羅列幾條.
1. 去除空白行
空白行是指空行或者只有空格的行,使用grep命令去除空白行,命令如下:
grep -v “^[[:space:]]*$” file
2. 實現or 和 and功能
1. grep -e 實現多個選項間的邏輯or關系
顯示shell類型為bash或者nologin的行:
grep -e bash -e nologin /etc/passwd
2. 兩次使用grep實現多個選項間的邏輯and關系
判斷用戶名為wang并且用戶ID為1007的用戶是否存在:
grep “^wang\>” /etc/passwd | cut -d: -f3 | grep “\<1007\>”
3. 過濾出段落中的IP地址
1. 顯示ifconfig命令結果中所有IPv4地址
ifconfig | egrep -o “\<(([0-9] | [1-9][0-9] | 1[0-9]{2} | 2[0-4][0-9] | 25[0-5]).){3}([0-9] | [1-9][0-9] | 1[0-9]{2} | 2[0-4][0-9] | 25[0-5])\>”
2. 顯示file文件中類似255.255.255.0 或者 114.114.114.119這樣的地址
ifconfig | egrep -o “\<(([0-9] | [1-9][0-9] | 1[0-9]{2} | 2[0-4][0-9] | 25[0-5]).)\1\1([0-9] | [1-9][0-9] | 1[0-9]{2} | 2[0-4][0-9] | 25[0-5])\>”
4. 對比grep和egrep中( )的使用區別
1. 用 grep 匹配 (jihui)
grep -o “(jihui)” f1
2. 用 egrep 匹配 (jihui)
egrep -o “\(jihui\)” f1
5. grep的多文件匹配
文件 f1 的內容為:
(jihui)
jihui
he he
(jihui)shi hen zhongyaodao(jihui)important
文件 f2 的內容為:
jihui is important
jihui
一次進行多文件的匹配,顯示在f1,f2文件中匹配jihui的行
grep “jihui” f1 f2
顯示的結果:
f1:(jihui)
f1:jihui
f1:(jihui)shi hen zhongyaodao(jihui)important
f2:jihui is important
f2:jihui
原創文章,作者:woking,如若轉載,請注明出處:http://www.www58058.com/83427