Linux正则表达式 - 删除"新行",但保持" CR +新行"?

时间:2017-10-16 20:53:15

标签: regex perl vim sed

cat -ev ./test.txt

1 line with "carriage return \r" and "new line \n"   ^M$
2 line only with "new line \n"   $
3  ^M$
4 line with "carriage return \r" and "new line \n"   ^M$
5 line with "carriage return \r" and "new line \n"   ^M$
6 line only with "new line \n"  $
7 line only with "new line \n"  $
8 line with "carriage return \r" and "new line \n"   ^M$

我想删除新的字符\ n \ n,但仅删除没有CR的行

所以输出应该是这样的:

1 line with "carriage return \r" and "new line \n"   ^M$
2 line only with "new line \n"   3  ^M$
4 line with "carriage return \r" and "new line \n"   ^M$
5 line with "carriage return \r" and "new line \n"   ^M$
6 line only with "new line \n"  7 line only with "new line \n"  8 line with "carriage return \r" and "new line \n"   ^M$

之后,是时候删除CR了。 最终输出:

1 line with "carriage return \r" and "new line \n"   $
2 line only with "new line \n"   3  $
4 line with "carriage return \r" and "new line \n"   $
5 line with "carriage return \r" and "new line \n"   $
6 line only with "new line \n"  7 line only with "new line \n"  8 line with "carriage return \r" and "new line \n"   $

最后一点很简单,例如在vim中:%s @ \ r @@ gc ...互联网上有很多提示"如何删除CR"

但我的问题是关于beginng - 如何删除" \ n"在perl和/或sed中,但只有没有CR的行?

2 个答案:

答案 0 :(得分:2)

您可以在Perl中同时执行这两个步骤:

perl -pe 's/(?<!\r)\n//; s/\r$//'

(如果没有回车符,则删除换行符;删除行尾的回车符。)

可替换地:

perl -pe 'chomp; s/\r\z/\n/'

(删除尾随换行符;用换行符替换最终回车符。)

第一个版本也适用于vim:

:%s/\r\@<!\n
:%s/\r$

(免责声明:我没有对此进行测试。)

答案 1 :(得分:2)

使用GNU awk的解决方案(使用记录分隔符):

awk 'BEGIN{RS=ORS="\r\n"}{gsub(/\n/,"")}1' test.txt