Stephan Stephan - 4 months ago 9
Linux Question

bash - How to replace line feeds in a variable?

Here is my script:

my_var="foo
bar
baz"

echo ${my_var//\n/\\n}


I want to replace all line feeds with
\\n
.

However here is what I have:

foo bar baz


What am I missing?

Answer

I think that this does what you want:

$ echo "${my_var//$'\n'/\\n}"
foo\nbar\nbaz

There are two important things to note:

  1. Quote your variables! Your expansion wasn't making any replacements but the whitespace in the variable was being squashed due to word-splitting. echo prints each of its arguments separated by a single space.
  2. Use $'\n' for a C-style string, to get a newline character in the search part of the expansion.