首页 > 解决方案 > 清除特定文本文件行的内容而不删除回车

问题描述

我有一个 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 在行中?

标签: windowssedreplacecarriage-return

解决方案


你能处理awk吗?:

测试源文件行尾:

$ 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

推荐阅读