Replace \ n (new line) with a space in bash

I am reading some sql queries in a variable from db and contains a new line character (\ n). I want to replace \ n (new line) with a space. I tried the solutions provided on the Internet, but could not achieve what I want. Here's what you tried:

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

my desired result is "my name is xxxx", but I get "my \ nname \ nis \ nxxxx". I also tried another solution provided online, but no luck:

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

Am I doing something?

+7
source share
1 answer

From bash:

Replace all newlines with a space:

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

Replace all lines with a \nspace:

nw_strr="${strr//\\n/ }"
+10
source

Source: https://habr.com/ru/post/1652797/


All Articles