Groovy: Read contents of a file in an array and grep for something
Asked Answered
K

2

3

I am trying to implement following in GROOVY script but getting errors: Read contents of an HTML file in an array and then grep for something in that array.

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;
}

Please review the code and suggest the correct method.

Keelia answered 23/5, 2017 at 11:10 Comment(1)
what error are you getting? is this in the context of a Jenkinsfile? can you post it?Zymogenic
C
4
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
Cowlick answered 23/5, 2017 at 12:43 Comment(4)
Withe this code i'm getting following error message: Scripts not permitted to use staticMethod org.codehaus.groovy.runtime.DefaultGroovyMethods readLines java.io.File. Am i missing anything?Keelia
seems you are in jenkins... I found this issue: issues.jenkins-ci.org/browse/JENKINS-35681 / seems there is a list of methods you are allowed to call. if you are inside pipeline - probably there are some native pipeline equivalents to load file content... and i found this github.com/jenkinsci/pipeline-examples/blob/master/docs/…Cowlick
Thanks @Cowlick for the references!Keelia
instead of using readLines function, one may split the file content and iterate over the array. This will not throw permission error. def lines= fileContent.split("\n") for (line in lines) {line=line.trim(); echo "$line";}Capitulation
E
2

you can try like this.

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");
}
Enterotomy answered 23/5, 2017 at 14:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.