简体   繁体   English

groovy 中的 grep 命令用法

[英]grep command usage in groovy

How to write the below shell 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 

<< edited in response to comment >> <<根据评论编辑>>

1. Pure Groovy Solution 1. 纯 Groovy 解决方案

If you just want to implement the functionality in your bash script in groovy, you can do something like this:如果您只想在 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"
}

should be noted that if your log file is large, there are better ways of searching for a string that do not require you to load the entire file into memory.应该注意的是,如果你的日志文件很大,有更好的方法来搜索一个不需要你将整个文件加载到内存中的字符串。

2. Process Management Solution 2.流程管理解决方案

If you were specifically looking to use the linux system grep command from within groovy, the above will naturally not help you.如果你特别想在 groovy 中使用 linux 系统的grep命令,那么上面的内容自然对你没有帮助。 The following groovy code:以下常规代码:

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
}

will execute the grep command and should get you closer to what you want.将执行grep命令并且应该让你更接近你想要的。

It should be noted that the output redirection > in your shell command is as far as I know hard to do on an external process from java/groovy and we are therefore writing the output to the final_output.log file from within groovy instead of executing the command using output redirection.应该注意的是,据我所知,shell 命令中的输出重定向>很难在 java/groovy 的外部进程上执行,因此我们将输出从 groovy 中写入final_output.log文件,而不是执行使用输出重定向的命令。

I also added a five second max timeout on the grep process execution.我还在grep进程执行中添加了 5 秒最大超时。 This is not required and that line can safely be removed, it's just there as a safeguard for cases where the grep blocks indefinitely.这不是必需的,并且可以安全地删除该行,它只是为了防止 grep 无限期阻塞的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM