我想按任意順序搜索大量文件集合,包含或不包含空格或標點符號。因此,舉例來說,如果我搜索hello, there, friend
,它應該匹配grep正則表達式:搜索任何一組單詞
hello there my friend
friend, hello there
theretherefriendhello
但不
hello friend
there there friend
我想不出任何辦法做到這一點。甚至有可能使用grep,或者grep的一些變體?
我想按任意順序搜索大量文件集合,包含或不包含空格或標點符號。因此,舉例來說,如果我搜索hello, there, friend
,它應該匹配grep正則表達式:搜索任何一組單詞
hello there my friend
friend, hello there
theretherefriendhello
但不
hello friend
there there friend
我想不出任何辦法做到這一點。甚至有可能使用grep,或者grep的一些變體?
是它甚至有可能用grep,或grep的一些變化呢?
你可以使用grep -P
ie即Perl
模式下面的正則表達式。
^(?=.*hello)(?=.*there)(?=.*friend).*$
查看演示。
爲此我wouldl使用awk
這樣的:
awk '/hello/ && /there/ && /friend/' file
此檢查當前行中包含所有字符串:hello
,there
和friend
。如果發生這種情況,行打印
爲什麼?因爲那麼條件爲True,並且當某些內容爲True時,awk的默認行爲是打印當前行。
在基本和擴展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的內置遞歸搜索方面很方便。如果再困擾你,我會用這個awk
或sed
相反,如果可以的話,包裹在find
:
find /path/ -exec awk '/hello/&&/there/&&/friend/ {r=1} END {exit 1-r}'\; -print
再次,這個輸出是一個文件列表,而不是行的列表。您可以調整以適應您的特定要求。
它必須是完全'你好'或'helloworld'也行嗎? – fedorqui 2015-04-01 17:44:24
'helloworld'沒問題,只要其他詞也在那裏。我會更新問題以澄清何時回到我的電腦。 – ewok 2015-04-01 17:46:52