【问题标题】:LF --> CR/LF conversion for UTF-16 fileLF --> UTF-16 文件的 CR/LF 转换
【发布时间】:2015-07-30 12:11:21
【问题描述】:

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

有没有linux命令行工具可以搜索两个字节“0A 00”并替换成四个字节“0D 00 0A 00”?

【问题讨论】:

  • 我已经尝试过“unix2dos”。它不起作用,因为它将“0A 00”替换为“OD 0A 00”!

标签: linux encoding command-line utf-16 line-endings


【解决方案1】:

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\0/\r\0\n\ 0/克;" 输出
  • @LarsSchneider:将:raw 添加到binmodes 有帮助吗?但是原版对我有用,你能展示一下xxd input.txt 返回的内容吗?
  • 喜欢这个? 'perl -we':raw:binmode STDIN, ":encoding(UTF-16le)"; :raw:binmode STDOUT, ":encoding(UTF-16le):crlf"; 时打印; '' ?
  • 给我:未加引号的字符串“raw”可能与 -e 第 1 行的未来保留字发生冲突。-e 第 1 行的语法错误,靠近“; :” 由于编译错误而中止 -e 的执行.
  • @LarsSchneider:不,':raw:encoding...。对我有用,有或没有 BOM,有或没有生的。
【解决方案2】:

您可以使用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

【讨论】:

    【解决方案3】:

    unix2dos 是您正在寻找的。查看其不同选项以找到适合您的 UTF-16 编码的选项。

    【讨论】:

      【解决方案4】:

      解决方案:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-07
        • 1970-01-01
        • 1970-01-01
        • 2019-03-14
        • 2010-12-04
        • 2020-09-24
        相关资源
        最近更新 更多