Remove newlines from string with tr
Asked Answered
A

1

5

I have a file that contains strings with newlines, like this:

{"name": "John\n\nMeyer"}
{"name": "Mary\n\nSmith"}

How can I remove them using the tr tool?

I'm trying this, but the output is bad:

$ cat f.json | tr -s '\\n\\n' ' '
{" ame": "Joh Meyer"}
{" ame": "Mary Smith"}

With Perl, that same regex works fine:

$ cat f.json | perl -pe 's/\\n\\n/ /g'
{"name": "John Meyer"}
{"name": "Mary Smith"}
Aloke answered 14/3, 2020 at 2:0 Comment(2)
You can't. tr substitutes single characters, not strings.Bombazine
Are you sure \\n are newlines and not two characters slash \ and n?Bombazine
B
7

Try the -d option of tr to delete characters:

tr -d \\n

Putting it all together:

cat f.json | tr -d \\n

You don't want the -s option. The -s option of tr means "squeeze". Squeeze removes the specified character if it appears more than once (leaving one).

Alternatively, to avoid using cat and pipe unnecessarily, you can just write the code like this:

tr -d \\n <f.json

One more note: If your input really doesn't have newlines but rather has a backslash followed by an 'en', you cannot use tr to remove them -- tr works on single characters.

Barkley answered 14/3, 2020 at 2:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.