Groovy multiline string keep new line and indentation

Viewed 186

If we have a multiline string in groovy, like this:

def multilineString = """
Lorem ipsum dolor sit amet,
        consectetur adipiscing elit,
        sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
"""

then using a simple println multilineString; will give an output for each line on a new line. Like this

Lorem ipsum dolor sit amet,
            consectetur adipiscing elit,
            sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.

I would like groovy to OUTPUT in the following format, keeping all the new line characters '\n', potentially tab characters '\t' and the indentation.

Desired output is a string on a single line that looks as follows:

Lorem ipsum dolor sit amet,\n consectetur adipiscing elit,\n sed do eiusmod tempor incididunt\nut labore et dolore magna aliqua.

Any help or suggestions would be appreciated. Completely new to groovy scripting.

1 Answers

You could use an approach like println multilineString.replaceAll('\n', '\\\\n')

Related