Rlearner
Rlearner

Reputation: 351

How to replace a pattern with newline (\n) with sed under UNIX / Linux operating systems?

I have a txt file which contains:

Some random
text here. This file
has multiple lines. Should be one line.

I use:

sed '{:q;N;s/\n/:sl:/g;t q}' file1.txt > singleline.txt

and get:

Some random:sl:text here. This file:sl:has multiple lines. Should be one line.

Now I want to replace the :sl: pattern with newline (\n) character. When I use:

sed 's/:sl:/&\n/g' singleline.txt

I get:

Some random:sl:
text here. This file:sl:
has multiple lines. Should be one line.

How to replace the pattern with newline character instead of adding newline character after the pattern?

Upvotes: 5

Views: 15576

Answers (2)

quantdev
quantdev

Reputation: 23813

You can do it more easily with tr : tr '\n' ' ' < singleline.txt

Upvotes: 1

miindlek
miindlek

Reputation: 3563

Sed uses & as a shortcut for the matched pattern. So you are replacing :s1: with :s1:\n.

Change your sed command like this:

sed 's/:sl:/\n/g' singleline.txt

Upvotes: 2

Related Questions