2008-12-08 68 views
3

我需要從一個file.txt文件中grep找到一堆名字,比如[email protected],[email protected]如何在groovy中使用grep中的變量?

file.txt有垃圾它是[email protected] [email protected]。我需要一旦我得到這些行,我需要到grep的Gmail和雅虎,並得到他們的計數

List l = new ArrayList{[email protected], [email protected]} 
def gmail = ['sh','-c','grep "clientLogin="$l.get(0) file.txt' | grep gmail | wc -l ] 
def yahoo = ['sh','-c','grep "clientLogin="$l.get(1) file.txt' | grep yahoo| wc -l ] 

這不工作,這些過濾掉

。我如何動態替換$ l.get(1)的值?


問題是,$ {l.get(0)}必須是裏面的 「」, 即:

def gmail = ['sh','-c','grep "clientLogin=${l.get(0)}" file.txt' | grep gmail | wc -l ] 

,使其看起來像:

def gmail = ['sh','-c','grep "[email protected]" file.txt' | grep gmail | wc -l ] 

clientLogin=${l.get(0)}不產生結果。我不知道我哪裏出錯了。

感謝您的建議,但不會產生結果,至少在我嘗試過時。


file.txt的有大量的垃圾和模式是這樣的:

Into the domain [email protected] exit on 12/01/2008 etc.. 

因此我

def ex = ['sh','-c','grep "domain clientLogin=$client" file.txt'| grep "something more" | wc -l] 

這樣我可以鏈上的grep的,因爲我想和最終登陸在我需要的數量。

我不知道如果我使用

def ex = ['grep', "$client", 'file.txt'] 

感謝您輸入我可以鏈裏grep。

回答

2

我不確定你需要'sh'和'-c'。我能得到這個工作:

def client = '[email protected]' 
def ex = ['grep', "$client", 'file.txt'] 

def proc = ex.execute() 
proc.waitFor() 

println "return: ${proc.exitValue()}" 
println "stderr: ${proc.err.text}" 
println "stdout: ${proc.in.text}" 

Groovy's documentation也可以幫助您與此有關。

0

您需要在變量表達式周圍使用{}。即:

"${l.get(0)}" 

有關更多信息,請參閱Groovy String文檔。

完整的示例:

List l = new ArrayList{[email protected], [email protected]} 
def gmail = ['sh','-c','grep "clientLogin="${l.get(0)} file.txt' | grep gmail | wc -l ] 
def yahoo = ['sh','-c','grep "clientLogin="${l.get(1)} file.txt' | grep yahoo| wc -l ] 
4

你已經使用Groovy,並使用正則表達式,給你你的答案的工作?

def file = new File("file.txt")  
file.delete() // clear out old version for multiple runs 
file << """ 
foobar [email protected] baz quux # should match [email protected] 
foobar [email protected] baz quux 
foobar [email protected] bal zoom 
foobar [email protected] baz quux # should match [email protected] 
foobar [email protected] bal zoom # should match [email protected] 
foobar [email protected] bal zoom 
""" 

def emailList = ["[email protected]", "[email protected]"] 
def emailListGroup = emailList.join('|') 
def pattern = /(?m)^.*clientLogin=($emailListGroup).*$/ 

def resultMap = [:] 

(file.text =~ pattern).each { fullLine, email -> 
    resultMap[email] = resultMap[email] ? resultMap[email] + 1 : 1 
} 

assert resultMap["[email protected]"] == 2 
assert resultMap["[email protected]"] == 1 

,感覺不是試圖掏出一個過程,並與清潔工作給我,再加上它只會挑選出與「ClientLogin的=(電子郵件)」,你要找的確切行。