22

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?

2

2 Answers 2

37

With bash:

Replace all newlines with a space:

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

Replace all strings \n with a space:

nw_strr="${strr//\\n/ }" 
Sign up to request clarification or add additional context in comments.

4 Comments

Works for me, but as John Kugelman mentions in his comment above, this must be tested with $strr containing an actual newline. For example strr=$'my\nname\nis\nxxxx'.
Second one works for me. I guess all \n come as string while reading from mysql.
This seems faulty. The second works for me if I don't put quotes around the substitution command. If I keep the quotes, the newlines remain. The first works for me regardless of whether I use quotes. Can you explain what the first is doing? And what difference it makes compared to the other?
@markling: Please show output of echo "$BASH_VERSION".
8

If you want to keep using pipes, you can do:

string_with_spaces=$(echo "$string_with_newlines" | tr '\n' ' ') 

Source.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.