2015-04-01 28 views
2

我想按任意順序搜索大量文件集合,包含或不包含空格或標點符號。因此,舉例來說,如果我搜索hello, there, friend,它應該匹配grep正則表達式:搜索任何一組單詞

hello there my friend 
friend, hello there 
theretherefriendhello 

但不

hello friend 
there there friend 

我想不出任何辦法做到這一點。甚至有可能使用grep,或者grep的一些變體?

+0

它必須是完全'你好'或'helloworld'也行嗎? – fedorqui 2015-04-01 17:44:24

+0

'helloworld'沒問題,只要其他詞也在那裏。我會更新問題以澄清何時回到我的電腦。 – ewok 2015-04-01 17:46:52

回答

2

是它甚至有可能用grep,或grep的一些變化呢?

你可以使用grep -P ie即Perl模式下面的正則表達式。

^(?=.*hello)(?=.*there)(?=.*friend).*$ 

查看演示。

https://regex101.com/r/sJ9gM7/37

2

您可以使用sed

sed -n '/word1/{/word2/{/word3/p;};}' *.txt 
+0

這適用於GNU sed,但不適用於OSX,FreeBSD等。爲了便於使用,在每個大括號('}')前加上一個分號(';')。 – ghoti 2015-04-01 18:00:13

+0

@ghoti非常感謝!很高興知道! – hek2mgl 2015-04-01 18:11:44

2

爲此我wouldl使用awk這樣的:

awk '/hello/ && /there/ && /friend/' file 

此檢查當前行中包含所有字符串:hellotherefriend。如果發生這種情況,行打印

爲什麼?因爲那麼條件爲True,並且當某些內容爲True時,awk的默認行爲是打印當前行。

2

在基本和擴展RE,不使用或於供應商特定版本的擴展如Perl RE,你將需要處理這個使用是這樣的:

egrep -lr 'hello.*there.*friend|hello.*friend.*there|there.*hello.*friend|there.*friend.*hello|friend.*hello.*there|friend.*there.*hello' /path/ 

注意-l選項來告訴你只有文件名和-r告訴grep遞歸搜索。此解決方案應適用於您可能遇到的幾乎所有grep變體。

這在RE方面顯然不夠優雅,但在使用grep的內置遞歸搜索方面很方便。如果再困擾你,我會用這個awksed相反,如果可以的話,包裹在find

find /path/ -exec awk '/hello/&&/there/&&/friend/ {r=1} END {exit 1-r}'\; -print 

再次,這個輸出是一個文件列表,而不是行的列表。您可以調整以適應您的特定要求。