Search code examples
jenkins

Jenkins convert multi line variable to single line


For our jenkins pipeline I have some script tags in which we runs commands, we run a command which returns a multi line result:

some_var = sh(returnStdout: true, script:  """some_command""").trim()

Later on I want to use the variable in a new command:

sh """different_command -v '${some_var}'"""

However some_var is a multi line result, but different_command takes a space separated value. I tried:

some_var = some_var.replace("[\n\r]*", "")

But this did not seem to do anything. How can I remove the new lines from a variable in jenkins and replace them with a space?


Solution

  • Your problem is with regex in replace. The pattern [\n\r]* is matching zero or more new lines or carriage returns. This might not catch all new lines.

    Better way is to use replaceAll method. Use pattern that finds all new lines and carriage returns and replace them with space. Here is how:

    some_var = some_var.replaceAll("[\n\r]+", " ")
    

    This pattern [\n\r]+ finds all \n or \r and replaces them with space. This gives you string with spaces for different_command.