grep的使用方法

今天被同事問到了如何用grep進行全詞匹配,通常用到的都是模糊查詢,通過度娘,用了下面的彙總code

grep 語法ip

grep 'word' filename
grep 'string1 string2'  filename
cat otherfile | grep 'something'
command | grep 'something'
command option1 | grep 'data'
grep --color 'data' fileName

基本的用法 在某個文件裏搜索error字符串字符串

$ grep "error" log.txt

忽略大小寫搜索(-i)string

$ grep -i "ErroR" log.txt

全部子目錄下的搜索(-r)pip

$ grep -r "exception" log.txt

全字匹配搜索(-w) 若是你搜索boo,查詢結果可能包含fooboo,boo123, booooom,等等,能夠使用**-w來限定全字匹配**io

$ grep -w "boo" /path/to/file

全字匹配搜索兩個不一樣單詞test

$ grep -w 'word1|word2' /path/to/file

統計字符串出現的次數(-c)file

$ grep -c 'word' /path/to/file

另外加-n的話, 會在結果中,列出匹配字符串的序列號,而且會列出內容搜索

$ grep -n 'word' /path/to/file

列出「不」包含字符串的行(-v)exception

$ grep -v bar /path/to/file

只列出文件名(-l)

$ grep -l 'main' *.pls

高亮顯示(--color)

$ grep --color sucre /var/log/vm/test.log

UNIX / Linux pipes + grep

ls -l | grep -i xyz

ls 列出當前目錄下的文件和文件夾,| 是管道傳遞給後面的一個程序,grep再是進行模式匹配

ls *.pls | grep -i --color "AA"
相關文章
相關標籤/搜索