如何将 ^M$ 换行符从 dos 转换为 unix(dos2unix 不起作用)

how to convert ^M$ newline from dos to unix (dos2unix didn't work)

正在尝试删除从 Windows 生成的错误换行符。

$cat -e file.xml
foo^M$
bar$
$
hello world1$
hello world2$

其中应该有 "foobar",中间没有任何换行符,而所有换行符都应该保留。 我知道在 emacs 中我们可以用 'RET' 替换“^M^J”,但我有一个巨大的文件,我不想打开它,只想使用命令行来转换它。

我试过 dos2unix,但它只删除了“^M”部分,仍然呈现损坏的 word/sentence。也尝试了 tr -d '\r'sed 's:^M$::g'sed 's:^M$\n:\n:g',都没有用。任何人都知道如何正确地做到这一点?

也许以下会起作用

sed -e 's/[\n\r]//g' old_file.txt > new_file.txt

会起作用

我已将您的示例文件复制为:

$ cat -e so.txt
foo^M$
bar$
line2$
line3$

您可以在 'gulp' 模式下使用 Perl 来做:

$ perl -0777 -pe 's/\r\n//g' so.txt
foobar
line2
line3

使用大多数面向行的方法的问题是 \r\n 被读取为一行。


你可以这样做:

$ perl -pe 's/\r\n//' /tmp/so.txt
foobar
line2
line3

还有...

使用awk

$ cat -e so.txt
foo^M$
bar$
line2$
line3$

$ awk 1 RS=$'\r\n' ORS= so.txt
foobar
line2
line3

$ awk 1 RS=$'\r\n' ORS= so.txt | cat -e # Just for verification
foobar$
line2$
line3$

它将记录分隔符设置为 \r\n 并打印带有 ORS=<empty string>

的记录