17

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?

Robert Columbia
  • 6,313
  • 15
  • 32
  • 40
Prometheus
  • 549
  • 1
  • 7
  • 18
  • 5
    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. – John Kugelman Aug 29 '16 at 05:08
  • See also: [Unix & Linux: Using `sed` to convert newlines into spaces](https://unix.stackexchange.com/q/26788/114401) – Gabriel Staples Aug 31 '23 at 03:36

1 Answers1

27

With bash:

Replace all newlines with a space:

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

Replace all strings \n with a space:

nw_strr="${strr//\\n/ }"
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • 1
    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'`. – Charley Aug 29 '16 at 05:15
  • Second one works for me. I guess all `\n` come as string while reading from mysql. – Prometheus Aug 29 '16 at 06:01