Julian
Julian

Reputation: 109

grep adds new line if splitted by groovy?

My goal is to get the names of x .conf files in a directory called "conf". My code looks like this:

commandOutput = sshCommand remote: getRemote(), command: getPathCmd(type) + "cd conf; ls | grep '.conf' | grep -Eo '^[a-zA-Z0-9_-]+'"
def instances = commandOutput.split("\n") as String[]
return instances

If i print the variable commandOutput (with two files in the directory) it shows me:

name1
name2

But when i make a for loop to print every slot of the array, i get this:

name1
*empty line*

and

name2

I checked commandOutput[0] with .endsWith("\n") and returned false so i dont know where the new line is coming from. Is there an obvious reason for that behaviour?

Edit: It also happens here:

command = getPathCmd(type) + getScript(type, "status") + "| grep -Eo '[0-9]{4,5}' | sort -u | grep -v '${params.xyID}\\|" + globalID + "'"
try{
    commandOutput = sshCommand remote: getRemote(), command: command
    def PIDs = commandOutput.split("\n") as String[]
    return PIDs
    
}
catch(Exception e){
    println("XY")
    return "XY"
}

Print of commandOutput:

1234
5678

For loop print of PIDs:

1234
*empty line*

and

5678

Upvotes: 0

Views: 435

Answers (1)

Julian
Julian

Reputation: 109

stringXY = stringXY.replaceAll("[\\\r\\\n]+",""); did the trick. It replaces all new lines.

tr '\n' '\0' as suggested in this thread wouldn't work here, because it would be harder to find out where one name ends and the next one starts.

Upvotes: 1

Related Questions