grep常用實例2019-11-7

grep命令用於搜索文本或指定的文件中與指定的字符串或模式相匹配的行,默認情況,grep命令只顯示匹配的行.

grep家族

  • grep: 在文件中全局查找指定的正則表達式,並打印所有包含該表達式的行
  • egrep: 擴展的egrep,支持更多的正則表達式元字符
  • fgrep: 固定grep(fixed grep),有時也被稱作快速(fast grep),它按字面解釋所有的字符

grep使用的元字符

grep: 使用基本元字符集

^, $, ., *, [], [^], < >,(),{}, +, |

egrep(或grep -E): 使用擴展元字符集

?, +, { }, |, ( )

注:grep也可以使用擴展集中的元字符,僅需要對這些元字符前置一個反斜線

  • \w 所有字母與數字,稱爲字符[a-zA-Z0-9]
'l[a-zA-Z0-9]*ve'	        
'l\w*ve'
  • \W 所有字母與數字之外的字符,稱爲非字符
'love[^a-zA-Z0-9]+' 	    
'love\W+'
  • \b 詞邊界
'\<love\>'		           
'\blove\b'

grep選項

選項 用途
-i, --ignore-case 忽略大小寫
-l, --files-with-matches 只列出匹配行所在的文件名
-n, --line-number 在每一行前面加上它在文件中的相對行號
-c, --count 顯示成功匹配的行數
-s, --no-messages 禁止顯示文件不存在或文件不可讀的錯誤信息
-q, --quiet, --silent 靜默–quiet, --silent
-v, --invert-match 反向查找,只顯示不匹配的行
-R, -r, --recursive 遞歸針對目錄
–color 顏色
-o, --only-matching 只顯示匹配的內容
-B, --before-context=NUM print NUM lines of leading context
-A, --after-context=NUM print NUM lines of trailing context
-C, --context=NUM print NUM lines of output context

grep 示例

grep -E 或 egrep

# egrep 'NW' datafile
# egrep 'NW' d*	
# egrep '^n' datafile
# egrep '4$' datafile
# egrep TB Savage datafile
# egrep 'TB Savage' datafile
# egrep '5\..' datafile	
# egrep '\.5' datafile		
# egrep '^[we]' datafile
# egrep '[^0-9]' datafile	
# egrep '[A-Z][A-Z] [A-Z]' datafile
# egrep 'ss* ' datafile		
# egrep '[a-z]{9}' datafile
# egrep '\<north' datafile
# egrep '\<north\>' datafile	
# egrep '\<[a-r].*n\>' datafile
# egrep '^n\w*\W' datafile	
# egrep '\bnorth\b' datafile
# egrep 'NW|EA' datafile
# egrep '3+' datafile
# egrep '2\.?[0-9]' datafile	
# egrep '(no)+' datafile
# egrep 'S(h|u)' datafile
# egrep 'Sh|u' datafile
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章