grep最先由肯·湯普遜寫成。原先是ed下的一個應用程序,名稱來自於g/re/p(globally search a regular expression and print,以正則進行全域查找以及打印)。在ed下,輸入g/re/p這個命令後,會將全部匹配‘定義樣式’的字符串,以行爲單位打印出,可是並不對原文件內容進行修改。 grep命令在對一個或多個文件的內容進行基於模式搜索的狀況下是很是有用的。模式能夠是單個字符、多個字符、單個單詞、或者是一個句子。固然最有用的仍是正則。
1 grep match_pattern file_name #標記匹配顏色加 --color=auto 選項
2 grep "match_pattern" file_name
grep "match_pattern" file_1 file_2 file_3 ...
root@linux:~# grep -l root /etc/passwd /etc/shadow /etc/fstab
grep "text" -n file_name
cat file_name | grep "text" -n
grep "text" -n file_1 file_2 #多個文件 使用正則表達式 -E 選項: grep -E "[1-9]+"
egrep "[1-9]+" 只輸出文件中匹配到的部分 -o 選項: echo this is a test line. | grep -o -E "[a-z]+\."
line. echo this is a test line. | egrep -o "[a-z]+\."
line.
grep -v "match_pattern" file_name
#只在目錄中全部的.php和.html文件中遞歸搜索字符 grep "main()" . -r --include *.{php,html} #在搜索結果中排除全部README文件 grep "main()" . -r --exclude "README" #在搜索結果中排除filelist文件列表裏的文件 grep "main()" . -r --exclude-from filelist
grep -r root /etc/ #上面的命令將會遞歸的在/etc目錄中查找「root」單詞
grep ^$ /etc/shadow #因爲/etc/shadow文件中沒有空行,因此沒有任何輸出
echo this is a text line | grep -e "is" -e "line" -o
is
is
line
cat patfile
aaa
bbb
echo aaa bbb ccc ddd eee | grep -f patfile -o
echo this is a text line |grep -E "is|line" -o
-E {}前面要的內容若是是多個字符,要用()包裹起來,不然只會匹配{}前面相連的單一字符
root@Linux:~# cat grep_file ^root root false$ root@Linux:~# grep -f grep_file /etc/passwd
root@Linux:~# grep -cf file /etc/passwd #cf參數的順序不能顛倒,file裏定義要匹配的模式 2
a)使用-B參數輸出匹配行的前4行 b)使用-A參數輸出匹配行的後4行 c)使用-C參數輸出匹配行的先後各4行
例15 -q 靜默輸出,用於測試php
echo gun is not unix | grep -bo "not" 7:not #一行中字符串的字符便宜是從該行的第一個字符開始計算,起始值爲0。選項 -b -o 通常老是配合使用。