Nick
Nick

Reputation: 2034

Convert file contents to a single line in ansible or jinja2 with \n characters replacing original newlines

I would like to take the contents of a file and print them as a single line string.

For example if I have a file with the following contents:

Line one
Line two

Line three

I would like an ansible / jinja2 template that will produce a variable with value:

Line one\nLine two\n\nLine three

When I use the contents of lookup('file', 'example.txt') the newlines are printed out instead of replaced by the text \n

The jinja2 filters I can think of usually do the reverse of this, to_nice_yaml or to_nice_json for example.

Upvotes: 2

Views: 2183

Answers (1)

Nick
Nick

Reputation: 2034

You can use the following to achieve this:

{{ lookup('file', 'example.txt') | replace('\n', '\\n') }}

Upvotes: 3

Related Questions