2011-05-06 61 views
31

如何使用Grep命令根據通配符file name搜索"LMN2011*"列出所有以此開頭的文件?根據文件名模式和文件內容列出文件名 - GREP?

我想添加對這些文件內容的另一個檢查。

如果file content有一個像

LMN20113456 

我可以使用GREP一些這方面的東西?

Grep -ls "LMN2011*" "LMN20113456" 

什麼是使用shell命令搜索文件名及其內容的正確方法?

回答

51

grep的不使用 「通配符」 搜索 - 這是貝通配,比如* .JPG。 Grep使用「正則表達式」進行模式匹配。而在shell中,'*'的意思是「任何東西」,在grep中,它意味着「匹配前一個項目零次或多次」。

更多信息和例子在這裏:http://www.regular-expressions.info/reference.html

要回答你的問題 - 你可以找到文件使用grep匹配某種模式:

find /somedir -type f -print | grep 'LMN2011' # that will show files whose names contain LMN2011 

然後你就可以搜索他們的內容(不區分大小寫):

find /somedir -type f -print | grep -i 'LMN2011' | xargs grep -i 'LMN20113456' 

如果路徑中可以包含空格,則應該使用「零終點」功能:

find /somedir -type f -print0 | grep -iz 'LMN2011' | xargs -0 grep -i 'LMN20113456' 
+0

如何將結果文件名寫入服務器 – zod 2011-05-06 17:29:57

7
grep LMN20113456 LMN2011* 

,或者如果你想通過子目錄遞歸搜索:

find . -type f -name 'LMN2011*' -exec grep LMN20113456 {} \; 
+0

我怎樣才能把結果寫入文件名到一個文本文件中的服務器 – zod 2011-05-06 17:30:03

+0

使用grep -l列出匹配的文件名而不是匹配的行,然後將輸出重定向到文件。 – 2011-05-06 22:46:19

0

find/folder -type f -mtime -90 | grep -E 「(.txt | .php | .inc | .root | .gif)」| xargs的ls -l命令> WWWlastActivity.log

23

可以毫不find通過用grep的"--include"選項來完成爲好。

grep的手冊頁說:

--include=GLOB 
Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). 

所以,做一個遞歸搜索字符串匹配特定模式的文件,它會是這個樣子:

grep -r --include=<pattern> <string> <directory> 

例如,在所有Makefiles中遞歸搜索字符串「mytarget」:

grep -r --include="Makefile" "mytarget" ./ 

或者要在所有文件中搜索start在文件名以「製作」荷蘭國際集團:

grep -r --include="Make*" "mytarget" ./ 
+0

中的文本文件中,很高興知道「如何在沒有查找的情況下完成」,實際上,只是爲了分享觀點 – Victor 2016-04-08 04:25:45

0

假設LMN2011*文件內/home/me/home/me/temp或低於跳過任何東西:

find /home/me -name 'LMN2011*' -not -path "/home/me/temp/*" -print | xargs grep 'LMN20113456'