【问题标题】:Groovy: Read contents of a file in an array and grep for somethingGroovy:读取数组中文件的内容并 grep 查找某些内容
【发布时间】:2017-05-23 11:10:39
【问题描述】:

我正在尝试在 GROOVY 脚本中实现以下功能,但出现错误: 读取数组中 HTML 文件的内容,然后通过 grep 读取该数组中的内容。

def file1 = new File("/path/to/the/file/xyz.html");
def lines = file1.readLines()
if ((-e "/path/to/the/file/xyz.html") and (!(grep /jira.bugtracker.com/, lines))
{
    println (" the changes are present\n");
    exit 0;
}
else
{
    println (" the changes are not present\n");
    exit 1;
}

请检查代码并提出正确的方法。

【问题讨论】:

  • 您遇到了什么错误?这是在 Jenkinsfile 的上下文中吗?可以发一下吗?

标签: jenkins groovy jenkins-pipeline groovyshell


【解决方案1】:
def file1 = new File("/path/to/the/file/xyz.html" )
def lines = file1.readLines()
def found = lines.find{ line-> line =~ /jira.bugtracker.com/ }
println ("the changes are ${ found ? '' : 'not ' }present")
return found ? 0 : 1

【讨论】:

  • 使用此代码,我收到以下错误消息:Scripts not permitted to use staticMethod org.codehaus.groovy.runtime.DefaultGroovyMethods readLines java.io.File。我错过了什么吗?
  • 似乎你在詹金斯......我发现了这个问题:issues.jenkins-ci.org/browse/JENKINS-35681 / 似乎有一个你可以调用的方法列表。如果您在管道内 - 可能有一些本地管道等价物来加载文件内容......我发现了这个github.com/jenkinsci/pipeline-examples/blob/master/docs/…
  • 感谢@daggett 的参考!
  • 可以不使用 readLines 函数,而是拆分文件内容并遍历数组。这不会引发权限错误。 def lines= fileContent.split("\n")for (line in lines) {line=line.trim(); echo "$line";}
【解决方案2】:

你可以这样试试。

if ( new File("/path/to/the/file/xyz.html").text?.contains("jira.bugtracker.com")){
   println (" the changes are present\n");
} else {
   println (" the changes are not present\n");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多