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

左心房为你撑大大i 提交于 2019-12-10 15:54:02

问题


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?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/23940591/how-to-replace-a-pattern-with-newline-n-with-sed-under-unix-linux-operating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!