Replace \n(new line) with space in bash
Asked Answered
M

2

20

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?

Mcguire answered 29/8, 2016 at 5:2 Comment(2)
For starters, as written $strr doesn't contain newlines, it contains literal backslash-N sequences. Try strr=$'my\nname\nis\nxxxx' to get proper newlines.Cissiee
See also: Unix & Linux: Using sed to convert newlines into spacesAcoustics
D
31

With bash:

Replace all newlines with a space:

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

Replace all strings \n with a space:

nw_strr="${strr//\\n/ }"
Despite answered 29/8, 2016 at 5:8 Comment(2)
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'.Mondragon
Second one works for me. I guess all \n come as string while reading from mysql.Mcguire
J
2

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

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

Source.

Jere answered 15/3 at 10:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.