LF --> CR/LF 转换为 UTF-16 文件

LF --> CR/LF conversion for UTF-16 file

我有一个 UTF-16 编码的文件,我想用 Windows 行结尾替换 UNIX 行结尾。我不想碰其他任何东西。

是否有linux命令行工具可以搜索两个字节“0A 00”并将其替换为四个字节“0D 00 0A 00”?

unix2dos 就是您要找的。查看它的不同选项以找到适合您的 UTF-16 编码的选项。

您可以使用unix2dos,但您必须先将文件转换为8位编码,然后再转换回UTF-16。明显的中间候选者是 UTF-8:

$ cat in.txt | iconv -f UTF-16 -t UTF-8 | unix2dos | iconv -f UTF-8 -t UTF-16 > out.txt

如果愿意,您可以将这三个管道命令包装在一个方便的脚本中。

#/bin/sh
iconv -f UTF-16 -t UTF-8 | unix2dos | iconv -f UTF-8 -t UTF-16

Perl 来拯救:

perl -we 'binmode STDIN,  ":encoding(UTF-16le)";
          binmode STDOUT, ":encoding(UTF-16le):crlf";
          print while <STDIN>;
        ' < input.txt > output.txt

解决方案:

perl -pe "BEGIN { binmode $_, ':raw:encoding(UTF-16LE)' for *STDIN, *STDOUT }; s/\n[=10=]/\r[=10=]\n[=10=]/g;" < input.file > output.file

感谢我的同事 Manu 和 Stream-process UTF-16 file with BOM and Unix line endings in Windows perl