假設我在文件中有一行「這也許是添加新功能最簡單的地方。」我想把兩個詞貼近對方。我做grep兩個詞彼此靠近
grep -ERHn "\beasiest\W+(?:\w+\W+){1,6}?place\b" *
工作,並給了我線。但是,當我做
grep -ERHn "\beasiest\W+(?:\w+\W+){1,10}?new\b" *
失敗,擊敗{1,10}的整點? 這是在regular-expression.info網站上列出的,也是一些Regex書籍。雖然他們沒有用grep來描述它,但那應該不重要。
更新
我把正則表達式轉換爲Python腳本。作品,但沒有漂亮的grep -C事情...
#!/usr/bin/python
import re
import sys
import os
word1 = sys.argv[1]
word2 = sys.argv[2]
dist = sys.argv[3]
regex_string = (r'\b(?:'
+ word1
+ r'\W+(?:\w+\W+){0,'
+ dist
+ '}?'
+ word2
+ r'|'
+ word2
+ r'\W+(?:\w+\W+){0,'
+ dist
+ '}?'
+ word1
+ r')\b')
regex = re.compile(regex_string)
def findmatches(PATH):
for root, dirs, files in os.walk(PATH):
for filename in files:
fullpath = os.path.join(root,filename)
with open(fullpath, 'r') as f:
matches = re.findall(regex, f.read())
for m in matches:
print "File:",fullpath,"\n\t",m
if __name__ == "__main__":
findmatches(sys.argv[4])
調用它作爲
python near.py charlie winning 6 path/to/charlie/sheen
爲我工作。
爲了方便,把這個在你的'.bashrc':'grepNear(){grep的-EHn 「\ b $ 1 \ W +(\ w + \ W +){1,10} $ 2 \ b」; }'。然後在bash提示符下:'echo「...」| grepNear最簡單的新「。 – 2017-01-05 22:09:28