Regex Linux正则表达式-删除";新行“;,但是,请保留“不”;CR和x2B;新行“;?

Regex Linux正则表达式-删除";新行“;,但是,请保留“不”;CR和x2B;新行“;?,regex,perl,vim,sed,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 "ne

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,但仅在没有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$
在那之后,是时候去除铬了。 最终输出:

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-如何在perl和/或sed中删除“\n”,但仅在没有CR的行中删除?

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

perl -pe 's/(?<!\r)\n//; s/\r$//'
(删除尾部换行符;用换行符替换最终回车符。)

第一版也可适用于vim:

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

(免责声明:我还没有测试过。)

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

perl -pe 's/(?<!\r)\n//; s/\r$//'
(删除尾部换行符;用换行符替换最终回车符。)

第一版也可适用于vim:

:%s/\r\@<!\n
:%s/\r$
:%s/\r\@
(免责声明:我尚未对此进行测试。)

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

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


@ikegami OP确实说过“Linux正则表达式”。-)我不是建议任何事情都应该改变。谢谢,它起作用了。最后一个问题-您知道如何在vim中执行此操作吗?:)我有错误:E486:找不到模式:(?@ikegami OP确实说了“Linux regex”。-)我没有建议任何东西应该更改。谢谢,它正在工作。最后一个问题-您知道如何在vim中执行此操作吗?:)我有一个错误:E486:找不到模式:(?您应该提到这是GNU awk,仅适用于多字符RS。您应该提到这是GNU awk,仅适用于多字符RS。