'In groovy, how can i iterate over a csv file and call a function for every "group" that as a different value on some of the columns?
In Groovy and running on a jenkins pipeline, I am using the readFile function from jenkins to read the csv file.
Example csv:
name | val1 | val2 |
---|---|---|
John | 2 | 122 |
John | 2 | 012 |
Bertha | 2 | 0021 |
John | 3 | 20 |
Philip | 3 | 12022 |
Bertha | 3 | 162021 |
John | 3 | 2022 |
What I am trying to achieve is call another function for each different value in column "name".
The Groovy script flow would be something like:
- call functionX (name, rest of values) with:
name | val1 | val2 |
---|---|---|
John | 2 | 122 |
John | 2 | 012 |
John | 3 | 20 |
John | 3 | 2022 |
- then call functionX (name, rest of values) with:
name | val1 | val2 |
---|---|---|
Philip | 3 | 12022 |
- then call functionX (name, rest of values) with:
name | val1 | val2 |
---|---|---|
Bertha | 2 | 0021 |
Bertha | 3 | 162021 |
Note: The order (John, Philip, Bertha) is not important!
I think i can achieve this with closures but I'm not quite sure since I'm pretty new to the topic
Solution 1:[1]
Is this something like what you are looking for?
def functionX(name,val1,val2) {
if (name == 'name') return
println ( "Name: $name, V1: $val1, V2: $val2" )
}
new File( 'names.csv' ).readLines().sort{ it }.each {
println it
functionX( *( it.split( ',' ) ) )
}
Output:
Bertha,2,21
Name: Bertha, V1: 2, V2: 21
Bertha,3,162021
Name: Bertha, V1: 3, V2: 162021
John,2,12
Name: John, V1: 2, V2: 12
John,2,122
Name: John, V1: 2, V2: 122
John,3,20
Name: John, V1: 3, V2: 20
John,3,2022
Name: John, V1: 3, V2: 2022
Philip,3,12022
Name: Philip, V1: 3, V2: 12022
name,val1,val2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |