Replace \n(new line) with space in bash

Prometheus picture Prometheus · Aug 29, 2016 · Viewed 11.5k times · Source

I am reading some sql queries into a variable from db and it contains new line character (\n). I want to replace \n (new line) with space. I tried solutions provided on internet but was unsuccessful to achieve what I want. Here is what tried :

strr="my\nname\nis\nxxxx";
nw_strr=`echo $strr | tr '\n' ' '`;
echo $nw_strr;

my desired output is "my name is xxxx" but what I am getting is "my\nname\nis\nxxxx". I also tried other solution provided at internet, but no luck:

nw_strr=`echo $strr | sed ':a;N;$!ba;s/\n/ /g'`;

Am I doing something wong?

Answer

Cyrus picture Cyrus · Aug 29, 2016

With bash:

Replace all newlines with a space:

nw_strr="${strr//$'\n'/ }"

Replace all strings \n with a space:

nw_strr="${strr//\\n/ }"