清除特定文本文件行的内容,但不删除回车符

问题描述 投票:0回答:1

我有一个DOS文本文件,我想从中清除所有以井号开头的行的内容。我想在每行中都保留回车符(CR),这与下面的代码不兼容。

据我理解,用“。*”表示,除换行符(LF)以外的任何字符都被视为。 CR也是如此,这就是为什么我的想法是用CR替换行内容。

这是我所拥有的:

sed.exe -e "s/^#.*/ \r/g" %1 >> result.txt

我希望发生的是例如文本文件:

hello you CRLF
#hello me CRLF
hello world CRLF

更改为

hello you CRLF
 CRLF
hello world CRLF

但是结果实际上是

hello you CRLF
 rLF
hello world CRLF

如何保持CR在行中?

windows sed replace carriage-return
1个回答
1
投票
测试源文件的行尾:

$ file file file: ASCII text, with CRLF line terminators

awk:

$ awk 'BEGIN{RS=ORS="\r\n"}{sub(/^\#.*/,"")}1' file > out

查看结果(0d 0a为CR LF):

$ hexdump -C out
00000000  68 65 6c 6c 6f 20 79 6f  75 0d 0a 0d 0a 68 65 6c  |hello you....hel|
00000010  6c 6f 20 77 6f 72 6c 64  0d 0a                    |lo world..|

解释:

$ awk '
BEGIN {               # set the record separators to CR LF
    RS=ORS="\r\n"     # both, input and output
}
{
    sub(/^\#.*/,"")   # replace # starting records with ""
}1' file > out        # output and redirect it to a file
© www.soinside.com 2019 - 2024. All rights reserved.