[英]sed replace multiple blank lines with single blank line
I have written a sed script, which replaces multiple blank lines with a single one, but it is not working as supposed to. 我编写了一个sed脚本,用一个替换多个空白行,但它没有按预期工作。 I will be thankful to everybody, who can explain me why. 我将感谢所有能解释我原因的人。 Please do not refer me to working examples, I am familiar with Google. 请不要参考我的工作示例,我熟悉Google。 I just want to understand how sed works. 我只是想了解sed是如何工作的。
The code is 代码是
sed ':a;/^\n*$/{N;ba};s/^\n\n*/\n/' input_file
so the logic is simple: when sed reads the line and it is either blank or has several newline symbols (this is /^*\\n$
condition), I tell sed to append the next line to pattern space. 所以逻辑很简单:当sed读取行并且它是空白或有几个换行符号(这是/^*\\n$
condition)时,我告诉sed将下一行附加到模式空间。 as soon as a non-blank line is found, the substitution s/^\\n\\n*/\\n/
is done. 一旦找到非空行,就完成替换s/^\\n\\n*/\\n/
。
Everything works fine except the cases when I have blank lines in the end of the file. 除了我在文件末尾有空行的情况外,一切正常。 These blanks are not replaced with a single blank and I do not understand why. 这些空白不会被一个空白所取代,我不明白为什么。
Any ideas? 有任何想法吗?
The problem is sed
getting EOF
while reading next line. 问题是sed
越来越EOF
同时读取下一行。
Your command is getting completed at the time of reading next line using N
. 在使用N
读取下一行时,您的命令已完成。 Because, While reading the next line, sed
getting EOF
. 因为,在阅读下一行时, sed
得到了EOF
。 So, It won't process s/^\\n\\n*/\\n/
substitution. 因此,它不会处理s/^\\n\\n*/\\n/
替换。 That is why, You are not able to remove sequence of empty lines which has appeared in end of file. 这就是为什么,你无法删除出现在文件末尾的空行序列。
My solution is: 我的解决方案是:
sed ':a; /^\n*$/{ s/\n//; N; ba};' yourfile
Instead of \\n\\n*
, you could use \\n+
而不是\\n\\n*
,您可以使用\\n+
By the way, this is what it would look like as a Perl one-liner: 顺便说一句,这就像Perl one-liner一样:
perl -0777 -pe 's/\n+/\n/g' yourfile
Or, for the same result but fewer substitutions: 或者,对于相同的结果但更少的替换:
perl -0777 -pe 's/\n\n+/\n/g' yourfile
Or, even more magical, try this compact solution suggested by @hwnd: 或者,更神奇的是,尝试@hwnd建议的这个紧凑的解决方案:
perl -00 -pe ''
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.