rohinee
rohinee

Reputation: 35

How to replace \n by space using sed command?

I have to collect a select query data to a CSV file. I want to use a sed command to replace \n from the data by a space.

I'm using this:

query | sed "s/\n/ /g" > file.csv .......

But it is not working. Only \ is getting removed, while it should also remove n and add a space. Please suggest something.

Upvotes: 1

Views: 3716

Answers (2)

Bohemian
Bohemian

Reputation: 424953

You want to replace newline with space, not necessarily using sed.

Use tr:

tr '\n' ' '

Upvotes: 2

Benjamin W.
Benjamin W.

Reputation: 52102

\n is special to sed: it stands for the newline character. To replace a literal \n, you have to escape the backslash:

sed 's/\\n/ /g'

Notice that I've used single quotes. If you use double quotes, the backslash has a special meaning if followed by any of $, `, ", \, or newline, i.e., "\n" is still \n, but "\\n" would become \n.

Since we want sed to see \\n, we'd have to use one of these:

  • sed "s/\\\n/ /g" – the first \\ becomes \, and \n doesn't change, resulting in \\n
  • sed "s/\\\\n/ /g" – both pairs of \\ are reduced to \ and sed gets \\n as well

but single quotes are much simpler:

$ sed 's/\\n/ /g' <<< 'my\nname\nis\nrohinee'
my name is rohinee

From comments on the question, it became apparent that sed had nothing to do with removing the backslashes; the OP tried

echo my\nname\nis | sed 's/\n/ /g'

but the backslashes are removed by the shell:

$ echo my\nname\nis
mynnamenis

so even if the correct \\n were used, sed wouldn't find any matches. The correct way is

$ echo 'my\nname\nis' | sed 's/\\n/ /g'
my name is

Upvotes: 1

Related Questions