########################## grep 使用 ###############
測試數據:
line1: What's that smell?
line2: What's that noise?
line3: What is this line for?
line4: What are you up to?
line5: May I ask you a question?
line6: What does "drowsy" mean?
line7: What's this?
line8: What's that?
line9: Who does this belong to?
line10: Which one?
#1 顯示匹配this行後再顯示下2行 (參數 -A)
grep this -A 2 testfile.txt
#2 顯示匹配this行周圍的上2行 (參數 -B)
grep -B 2 this testfile.txt
顯示匹配May行上下2行
grep May -B 2 -A 2 test
#3 顯示匹配行上下各2行 相當於上面(AB)組合 (參數 -C)
grep -C 2 drowsy testfile.txt
#4 忽略二進制文件搜索 (參數 -I)
grep this -I testfile.txt
#5 顯示匹配加顏色 (參數 --colour)
grep this --colour=auto testfile.txt
或者
export GREP_COLOR='1;32'
grep this --colour=auto testfile.txt
#6 計算匹配成功多少行 (參數 -c)
grep -c What testfile.txt
#7 顯示過濾掉this 即:顯示不匹配的行 (參數 -v)
grep -v 'this' testfile.txt
#8 搜索套接字、管道和銷售隊列等 (參數 -D ACTION)
#9 正則表達式搜索 (參數 -E) 相當於egrep
grep -E 'What|May' testfile.txt
grep -v -E 'Wh|this' testfile.txt
#10 輸出匹配行的同時輸出所屬文件名 (參數 -H)
grep -H -E 'this|ye' testfile1.txt testfile.txt
grep -HEn 'this|ye' testfile1.txt testfile.txt
#11 輸出匹配行的不輸出所屬文件名 (參數 -h)
grep -E -h 'this|ye' testfile.txt testfile1.txt
#12 忽略大小寫 (參數 -i)
grep wh -i testfile.txt
#13 顯示不匹配的文件名(搜索出那些文件不包含匹配yeqing) (參數 -L)
grep yeqing -L testfile*
#14 顯示匹配的文件名 (哪些文件包含匹配 yeqing) (參數 -l)
grep yeqing -l testfile*
#15 搜索最多匹配行(參數 -m)
grep yeqing -m 2 testfile.txt
#16 打印匹配的行號 (參數 -n)
grep Wh -n testfile.txt
#17 只顯示匹配的部分
grep -o this testfile.txt
#18 不打印,搜索到返回0 (參數 -q)
grep -q ye testfile1.txt
echo $?
#19 忽略錯誤信息 (參數 -s)
[root@home-backup scripts]# grep -s sss ss./a
[root@home-backup scripts]# grep sss ss./a
grep: ss./a: 沒有那個文件或目錄
#20 簡單正則
##1 以yeqing開頭的匹配
grep '^yeqing' test
##2 以yeqing結尾的匹配
grep 'yeqing$' test
##3 匹配一個指定範圍內的字符
grep '[qM]' test
##4 匹配第一個字符範圍是A到Z,第二個字符範圍是0-9,第三個字符是yeqing的行
grep '[A-Z][0-9]yeqing' test
待續......
參考資料:
http://www.gnu.org/software/grep/manual/grep.html
http://www.debian-administration.org/articles/460
http://www.regular-expressions.info/posix.html