pablomolnar pablomolnar - 27 days ago 10
Bash Question

How to display a file with multiple lines as a single string with escape chars (\n)

In bash, how I can display the content of a file with multiple lines as a single string where new lines appears as

\n
.

Example:

$ echo "line 1
line 2" >> file.txt


I need to get the content as this
"line 1\nline2"
with bash commands.

I tried using a combinations of
cat/printf/echo
with no success.

Answer

You can use printf to get something close:

$ printf "%q" $(< file.txt)"
$'line1\nline2'

and in bash 4.4 there is a new parameter expansion operator to produce the same:

$ foo=$(<file.txt)
$ echo "${foo@Q}"
$'line1\nline2'