0

I have input data of type

abc    12d
uy     76d
ce     12a

with the lines being separated by \n and the values by \t.

The data comes from a shell command:

brlist = 'mycommand'.execute().text

Then I want to get this into a map:

brmap = brlist.split("\n").collectEntries {
          tkns = it.tokenize("\t")
          [ (tkns[0]): tkns[1] ]
        }

I also tried

brmap = brlist.split("\n").collectEntries {
          it.tokenize("\t").with { [ (it[0]): it[1] ] }
        }

Both ways gave the same result, which is a map with a single entry:

brmap.toString()
# prints "[abc:12d]"

Why does only the first line of the input data end up being in the map?

Stefan Seidel
  • 9,421
  • 3
  • 19
  • 18

3 Answers3

1

Your code works, which means the input String brlist isn't what you say it is...

Are you sure that's what you have? Try printing brlist, and then it inside collectEntries

As an aside, this does the same thing as your code:

brlist.split('\n')*.split('\t')*.toList().collectEntries()

Or you could try (incase it's spaces not tabs, this will expect both)

brlist.split('\n')*.split(/\s+/)*.toList().collectEntries()
tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • That code doesn't run. I'm using the Jenkins Groovy Pipeline script. `groovy.lang.MissingMethodException: No signature of method: [Ljava.lang.String;.split() is applicable for argument types: (java.lang.String) values: [ ] Possible solutions: split(groovy.lang.Closure), wait(), init(), sort(), tail(), toList()` – Stefan Seidel Oct 20 '16 at 15:37
1

This code works

// I use 4 spaces as tab.
def text = 'sh abc.sh'.execute().text.replaceAll(" " * 4, "\t")
brmap = text.split("\n").collectEntries {
    tkns = it.tokenize("\t")
    [(tkns[0]) : tkns[1]]
}
assert[abc:"12d", uy:"76d", ce:"12a"] == brmap

abc.sh

#!/bin/sh
echo "abc    12d"
echo "uy    76d"
echo "ce    12a

Also, I think your groovy code is correct. maybe your mycommand has some problem.

koji
  • 179
  • 6
0

Ok, thanks for the hints, it is a bug in Jenkins: https://issues.jenkins-ci.org/browse/JENKINS-26481.

And it has been mentioned here before: Groovy .each only iterates one time

Community
  • 1
  • 1
Stefan Seidel
  • 9,421
  • 3
  • 19
  • 18