groovy - 我如何在 groovy 的 grep 中使用变量?

标签 groovy grep

我需要从 file.txt 中 grep 查找带有一堆名称的行,例如 clientLogin=a@yahoo.comclientLogin=b@gmail.com

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

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

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 ]

这行不通。如何动态替换 $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 "clientLogin=a@yahoo.com" file.txt' | grep gmail | wc -l ]

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

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


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

Into the domain clientLogin=a@yahoo.com exit on 12/01/2008 etc..

所以我做

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

这样我就可以根据需要链接 grep,并最终达到我需要的计数。

我不确定如果我使用

是否可以链接 greps
def ex = ['grep', "$client", 'file.txt']

感谢您的输入。

最佳答案

您已经在使用 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

对我来说,这比尝试提取一个流程并使用它更干净,而且它只会挑选出您正在寻找的带有“clientLogin=(email)”的确切行。

关于groovy - 我如何在 groovy 的 grep 中使用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/350620/

相关文章:

java - java对象在groovy中编码时可以访问它们的实例方法吗?

grails - 动态Groovy上传到Grails应用程序

git - 如何获取 Git 的最新稳定版本号?

java - groovy sql withbatch 的问题

inheritance - Groovy 中函数覆盖和可选参数的奇怪行为

linux - 在几个文件中搜索一大段有特殊字符的字符串并替换

linux - Bash 脚本 : Using grep to find a string that is also an option

regex - 使用 grep 等 bash 工具解决难题

Linux 服务器,定位只包含 4 个特定行的文件

grails - 我可以将参数从 Controller 传递到服务类吗