2013-02-09 157 views
3

我希望到grep在一個文件中的以下字符串:grep的使用通配符

directory1 
directory2 
directory3 

有沒有辦法到grep可同時使用grep所有3?

例如:

cat file.txt | grep directory[1-3] 

不幸的是,上述不工作

回答

6

如果這些是你需要搜索,使用-F(grep的固定字符串)唯一的字符串:

grep -F "directory1 
directory2 
directory3" file.txt 

如果你想grep使用更高級的正則表達式,使用-E(使用擴展正則表達式):

grep -E 'directory[1-3]' file.txt 

請注意,某些grep(如GNU grep)在本示例中不需要-E

最後,請注意,您需要引用正則表達式。如果你不這樣做,你的shell有可能首先根據路徑名擴展來擴展正則表達式(例如,如果你在當前目錄下有一個名爲「directory1」的文件/目錄,你的shell將把grep directory[1-3]變成grep directory1)。

0

您測試了哪個shell?

這裏

grep directory[1-3]作品對於bash,並不下的zsh

工作

你可以報價"directory[1-3]"

或逃避grep directory\[1-3\]

bash v4.2 
zsh v5.0.2 
grep (GNUgrep 2.14) 
0

這不是很漂亮,但你可以鏈接grep在一起: grep -l「directory1」./*.txt|xargs grep -l「d irectory2「| xargs grep -l」directory3「

限制您的輸入以提高性能,例如使用find: 查找./*.txt -type f | xargs grep -l」directory1「| xargs grep -l 「directory2」| xargs grep -l「directory3」