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.

Yash
  • 2,944
  • 7
  • 25
  • 43

2 Answers2

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
daggett
  • 26,404
  • 3
  • 40
  • 56
  • 1
    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? – Yash May 24 '17 at 11:37
  • seems you are in jenkins... I found this issue: https://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 https://github.com/jenkinsci/pipeline-examples/blob/master/docs/BEST_PRACTICES.md – daggett May 24 '17 at 12:41
  • Thanks @daggett for the references! – Yash May 24 '17 at 12:49
  • 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";}` – Manish Bansal Jan 27 '20 at 09:53
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");
}
sfgroups
  • 18,151
  • 28
  • 132
  • 204