2017-03-07 120 views
5

我使用以下命令在目錄結構中遞歸查找字符串。在Unix中使用find命令時忽略「是目錄」結果

find . -exec grep -l samplestring {} \; 

但是,當我一個大目錄結構中運行命令,將有

grep: ./xxxx/xxxxx_yy/eee: Is a directory 
grep: ./xxxx/xxxxx_yy/eee/local: Is a directory 
grep: ./xxxx/xxxxx_yy/eee/lib: Is a directory 

一個長長的清單我想省略上述結果。只需顯示字符串即可獲取文件名。有人可以幫忙嗎?

回答

3

每當你說find .,該實用程序將當前目錄結構中返回的所有元素:文件,目錄,鏈接...

如果你只是想找到的文件,只是這麼說!

find . -type f -exec grep -l samplestring {} \; 
#  ^^^^^^^ 

但是,您可能希望找到包含字符串的所有文件說:

grep -lR "samplestring" 
+2

'find -type f'和'grep -r'或'grep -R'是不錯的選擇......只是爲了完成答案,或許加上'-d skip'專門照顧'是一個目錄'問題......至少在使用遞歸搜索的shell選項的情況下,例如'grep -d skip -l'samplestring'**/@(* .txt | * .log)' – Sundeep

+1

@Sundeep不錯!我不知道'-d'標誌。 – fedorqui

3

grep -sgrep --no-messages

這是值得一讀的可移植性the GNU grep documentation指出,如果你希望使用不過這個代碼有多個地方:

-s --no-messages Suppress error messages about nonexistent or unreadable files. Portability note: unlike GNU grep, 7th Edition Unix grep did not conform to POSIX, because it lacked -q and its -s option behaved like GNU grep’s -q option.1 USG-style grep also lacked -q but its -s option behaved like GNU grep’s. Portable shell scripts should avoid both -q and -s and should redirect standard and error output to /dev/null instead. (-s is specified by POSIX.)

+0

我不認爲這是有用的隱藏錯誤,當你可以避免它們。看到我的答案 – fedorqui