Kiran234567
Kiran234567

Reputation: 43

Jenkins Pipeline failed to read data line by line

I am trying to read data(multiline of key:value pair) from file, which I have written line by line to file, In Jenkinfile However when I tried to do each line it is read char by char

Example:
echo "1234:34" >> dataList.txt
echo "2341:43" >> dataList.txt
echo "3412:54" >> dataList.txt
echo "4123:38" >> dataList.txt

When I tried to read line by line using commands

def buildData = readFile(file: "dataList.txt")
            println buildData
            buildData.each { line -> 
                println line
                //def (oldBuildNumber, oldJobId) =line.tokenize(':')
                //println oldBuildNumber oldJobId
                
            }
}

displaying as

1
2
3
4
:
3
4

2
3
4
1
:
4
3
...


Any input on this will be very useful.

Upvotes: 0

Views: 681

Answers (1)

Noam Helmer
Noam Helmer

Reputation: 6849

From the readFile documentation:

readFile: Read file from workspace
Reads a file from a relative path (with root in current directory, usually workspace) and returns its content as a plain string.

This means the the returned value, buildData in your case, is actually a string, and therefore when you iterate over it using the each you are actually iterating over the characters (as a characters array) and that is why you see each character being printed for each iteration.

What you actually want is to iterate over the lines, for that you can split the string using the new line separator (\n) which will give you a list of all lines which you can then iterate over.

Something like the following:

def buildData = readFile(file: "dataList.txt")
println buildData

// split the content into lines and go over each line
buildData.split("\n").each { line -> 
    println line 
}

// or by using the default iterator parameter - it
buildData.split("\n").each { 
    println it 
}

Upvotes: 2

Related Questions