[英]grep command usage in groovy
如何在 groovy 中编写下面的 shell
process_name = spin_user
if grep -i ${process_name} /tmp/output.log ; then
echo "Success"
grep -i ${process_name} output.log > final_output.log
else
echo "failure"
fi
<<根据评论编辑>>
1. 纯 Groovy 解决方案
如果您只想在 groovy 中实现 bash 脚本中的功能,可以执行以下操作:
def processName = 'spin_user'
def outLog = new File('/tmp/output.log')
def finalLog = new File('final_output.log')
def lines = outLog.readLines()
def hasProcess = { it.toLowerCase().contains(processName) }
if(lines.any(hasProcess)) {
println "Sucess"
finalLog.text = lines.findAll(hasProcess).join('\n')
} else {
println "failure"
}
应该注意的是,如果你的日志文件很大,有更好的方法来搜索一个不需要你将整个文件加载到内存中的字符串。
2.流程管理解决方案
如果你特别想在 groovy 中使用 linux 系统的grep
命令,那么上面的内容自然对你没有帮助。 以下常规代码:
import java.util.concurrent.*
def processName = 'spin_user'
def outLog = '/tmp/output.log'
def finalLog = 'final_output.log'
def result = exec('grep', '-i', processName, outLog)
if (result) {
println "success"
new File(finalLog).text = result
} else {
println "failure"
}
String exec(String... args) {
def out = new StringBuffer()
def err = new StringBuffer()
def process = args.toList().execute()
process.consumeProcessOutput(out, err)
process.waitForOrKill(5000)
if (err) {
println "ERROR: executing ${args} returned ${process.exitValue()}"
println "STDERR: ${err}"
}
out
}
将执行grep
命令并且应该让你更接近你想要的。
应该注意的是,据我所知,shell 命令中的输出重定向>
很难在 java/groovy 的外部进程上执行,因此我们将输出从 groovy 中写入final_output.log
文件,而不是执行使用输出重定向的命令。
我还在grep
进程执行中添加了 5 秒最大超时。 这不是必需的,并且可以安全地删除该行,它只是为了防止 grep 无限期阻塞的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.