【问题标题】:Linux regex - remove "new line", but keep "CR + new line"?Linux regex - 删除“新行”,但保留“CR + 新行”?
【发布时间】:2018-03-28 11:35:41
【问题描述】:

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$

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

【问题讨论】:

    标签: regex perl vim sed


    【解决方案1】:

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

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

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

    或者:

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

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

    第一个版本也可以适配vim:

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

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

    【讨论】:

    • @ikegami OP 确实说过“Linux regex”。 :-)
    • 我并没有建议应该改变什么。
    • 谢谢,它正在工作。最后一个问题 - 你知道如何在 vim 中做到这一点吗? :) 我有错误:E486: Pattern not found: (?
    【解决方案2】:

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

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

    【讨论】:

    • 您应该提到的是 GNU awk 仅适用于多字符 RS。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 2023-04-03
    • 1970-01-01
    • 2017-05-24
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    相关资源
    最近更新 更多