歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Linux/Unix下grep命令使用的幾個例子[grep Examples]

Linux/Unix下grep命令使用的幾個例子[grep Examples]

日期:2017/2/28 15:47:36   编辑:Linux教程

Linux/Unix下grep 語法

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)

$ grep -i "ErroR" log.txt


所有子目錄下的搜索(-r)

$ grep -r "exception" log.txt


全字匹配搜索(-w)

如果你搜索boo,查詢結果可能包含fooboo,boo123, booooom,等等,可以使用-w來限定全字匹配
$ grep -w "boo" /path/to/file


全字匹配搜索兩個不同單詞

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


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

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

另外加-n的話, 會在結果中,列出匹配字符串的序列號,並且會列出內容
$ grep -n 'word' /path/to/file


列出“不”包含字符串的行(-v)

$ grep -v bar /path/to/file


只列出文件名(-l)

$ grep -l 'main' *.pls


高亮顯示(--color)

$ grep --color Oracle /etc/passwd


UNIX / Linux pipes + grep

ls -l | grep -i xyz

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

例如:ls *.pls | grep -i --color "MM"

========EOF=========

Copyright © Linux教程網 All Rights Reserved