Stephan Stephan - 10 months ago 28
Linux Question

bash - How to replace line feeds in a variable?

Here is my script:


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

I want to replace all line feeds with

However here is what I have:

foo bar baz

What am I missing?


I think that this does what you want:

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

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.