Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace \n(new line) with space in bash

Tags:

bash

sed

tr

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?

like image 788
Prometheus Avatar asked Aug 29 '16 05:08

Prometheus


People also ask

How do I replace a line in bash?

The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.


1 Answers

With bash:

Replace all newlines with a space:

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

Replace all strings \n with a space:

nw_strr="${strr//\\n/ }"
like image 103
Cyrus Avatar answered Sep 19 '22 17:09

Cyrus