在shell命令行中将两个换行符替换为一个 [英] replace two newlines to one in shell command line
问题描述
关于将多个换行符替换为一个换行符存在很多问题,但是没有人为我工作.
我有一个文件:
There are lot of questions about replacing multi-newlines to one newline but no one is working for me.
I have a file:
first line
second line MARKER
third line MARKER
other lines
many other lines
我需要将MARKER
之后的两个换行符替换为一个换行符.结果文件应为:
I need to replace two newlines (if they exist) after MARKER
to one newline. A result file should be:
first line
second line MARKER
third line MARKER
other lines
many other lines
我尝试了sed ':a;N;$!ba;s/MARKER\n\n/MARKER\n/g'
失败.
sed
对于单行替换很有用,但换行符有问题.找不到\n\n
I tried sed ':a;N;$!ba;s/MARKER\n\n/MARKER\n/g'
Fail.
sed
is useful for single line replacements but has problems with newlines. It can't find \n\n
我尝试了perl -i -p -e 's/MARKER\n\n/MARKER\n/g'
失败.
这个解决方案看起来更近了,但是似乎regexp对\n\n
没有反应.
I tried perl -i -p -e 's/MARKER\n\n/MARKER\n/g'
Fail.
This solution looks closer, but it seems that regexp didn't reacts to \n\n
.
是否可以仅在MARKER
之后替换\n\n
而不能替换文件中的其他\n\n
?
我对单行解决方案感兴趣,而不是脚本.
Is it possible to replace \n\n
only after MARKER
and not to replace other \n\n
in the file?
I am interested in one-line-solution, not scripts.
推荐答案
我认为您的做法正确.在多行程序中,您会将整个文件加载到单个标量中,然后在其上运行此替换:
I think you were on the right track. In a multi-line program, you would load the entire file into a single scalar and run this substitution on it:
s/MARKER\n\n/MARKER\n/g
使单线加载文件到多行字符串的诀窍是在BEGIN
块中设置$/
.在读取输入之前,该代码将执行一次.
The trick to getting a one-liner to load a file into a multi-line string is to set $/
in a BEGIN
block. This code will get executed once, before the input is read.
perl -i -pe 'BEGIN{$/=undef} s/MARKER\n\n/MARKER\n/g' input
这篇关于在shell命令行中将两个换行符替换为一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!