Yash
Yash

Reputation: 3114

Groovy: Read a line from a text file into an array using groovy

Context: I'm writing a jenkins file in which i want to read an Input_params.txt file, search for a keyword then, print the values of the keyword into an array and then print each element of the array.

The contents of input params (format is "KEY:VALUE") file are:

sh> cat Input_params.txt
SOME_DETAILS:1234-A0;1456-B1;2456-B0;3436-D0;4467-C0

Step-1: Store the SOME_DETAILS in an array:

Integer[] testArray = ["1234-A0", "1456-B1", "2456-B0" , "3436-D0" , "4467-C0"]

Step-2: print the elements of the array sequentially. For example:

testArray.each {
println "chip num is ${it}"
}

Sample code:

println ("Check if the "Key:Value" is present in the Input_params.txt \n");
if ( new File("$JobPath/Input_params.txt").text?.contains("SOME_DETAILS"))
{
   println ("INFO: "Key:Value" is present in the info_file.txt \n");
  >>>>> Code to write the "value" of line with key "SOME_DETAILS" into an array here.. <<<<< 
}

I need help in writing the Code to write the "value" of line with key "SOME_DETAILS" into an array.

Upvotes: 0

Views: 6211

Answers (2)

daggett
daggett

Reputation: 28564

def testArray=[]
new File("/11/tmp/1.txt").splitEachLine("[:;]"){line->
    if(line[0]=='SOME_DETAILS')testArray=line[1..-1]
}
println testArray

Upvotes: 1

Mike W
Mike W

Reputation: 3932

Maybe something like:

def theFile = new File("$JobPath/Input_params.txt")

def linesWithDetails = theFile.findAll {
    it.contains 'SOME_DETAILS'
}

Upvotes: 0

Related Questions