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

11,159

Solution 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

Solution 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");
}
Share:
11,159

Related videos on Youtube

Yash
Author by

Yash

Updated on June 04, 2022

Comments

  • Yash
    Yash almost 2 years

    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.

    • burnettk
      burnettk almost 7 years
      what error are you getting? is this in the context of a Jenkinsfile? can you post it?
  • Yash
    Yash almost 7 years
    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?
  • daggett
    daggett almost 7 years
    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/…
  • Yash
    Yash almost 7 years
    Thanks @daggett for the references!
  • Manish Bansal
    Manish Bansal about 4 years
    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";}