如何在grop中使用grep中的变量?

aad*_*asu 3 groovy grep

我需要到grep用一串名字,说的线clientLogin=a@yahoo.com,clientLogin=b@gmail.com从file.txt的.

file.txt有垃圾email=a@yahoo.com email=b@gmail.com.我需要过滤掉这些

一旦我得到这些行,我需要grep gmail和yahoo并获得他们的计数

List l = new ArrayList{a@yahoo.com, b@gmail.com}
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 ]
Run Code Online (Sandbox Code Playgroud)

这不起作用.如何动态替换$ l.get(1)值?


问题是$ {l.get(0)}必须在""内,即:

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

所以它看起来像:

def gmail = ['sh','-c','grep "clientLogin=a@yahoo.com" file.txt' | grep gmail | wc -l ]
Run Code Online (Sandbox Code Playgroud)

clientLogin=${l.get(0)}不会产生结果.我不确定我哪里出错了.

感谢您的建议,但它不会产生结果,至少在我尝试时.


file.txt有很多垃圾和类似的模式:

Into the domain clientLogin=a@yahoo.com exit on 12/01/2008 etc..
Run Code Online (Sandbox Code Playgroud)

因此,我做到了

def ex = ['sh','-c','grep "domain clientLogin=$client" file.txt'| grep "something more" | wc -l]
Run Code Online (Sandbox Code Playgroud)

这样我可以按照自己的意愿链接grep并最终降落在我需要的数量上.

如果我使用的话,我不确定是否可以连接greps

def ex = ['grep', "$client", 'file.txt']
Run Code Online (Sandbox Code Playgroud)

感谢您的输入.

Ted*_*eid 5

你已经在使用groovy,使用正则表达式给你答案吗?

def file = new File("file.txt")    
file.delete() // clear out old version for multiple runs
file <<  """
foobar clientLogin=a@yahoo.com baz quux   # should match a@yahoo.com
foobar email=a@yahoo.com baz quux
foobar email=b@gmail.com bal zoom
foobar clientLogin=a@yahoo.com baz quux   # should match a@yahoo.com
foobar clientLogin=b@gmail.com bal zoom   # should match b@gmail.com
foobar email=b@gmail.com bal zoom
"""

def emailList = ["a@yahoo.com", "b@gmail.com"]
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["a@yahoo.com"] == 2
assert resultMap["b@gmail.com"] == 1
Run Code Online (Sandbox Code Playgroud)

这对我来说比尝试使用流程并使用它更加清晰,而且它只会选择您正在寻找的"clientLogin =(email)"的确切行.