【问题标题】:How to replace invalid UTF8 chars with spaces如何用空格替换无效的 UTF8 字符
【发布时间】:2014-03-19 16:18:19
【问题描述】:

我有一个固定宽度的文件,其中包含一些非 UTF8 字符,我想用空格替换非 UTF8 字符。

我尝试运行iconv -f utf8 -t utf8 -c $file 但它唯一会删除非 UTF8 字符。使用 iconv 无法将它们替换为空格。

我想要一个 korn shell 脚本/perl 脚本来用空格替换所有非 utf8 字符。

我发现了这个 perl 脚本,它打印了找到非 utf8 字符的行,但我不知道 perl 如何用空格替换非 UTF8。

perl -l -ne '/
   ^( [\000-\177]                 # 1-byte pattern
     |[\300-\337][\200-\277]      # 2-byte pattern
     |[\340-\357][\200-\277]{2}   # 3-byte pattern
     |[\360-\367][\200-\277]{3}   # 4-byte pattern
     |[\370-\373][\200-\277]{4}   # 5-byte pattern
     |[\374-\375][\200-\277]{5}   # 6-byte pattern
    )*$ /x or print' FILE.dat

环境 AIX

【问题讨论】:

    标签: perl unix utf-8


    【解决方案1】:

    Perl 的 Encode 模块有这个能力。

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use Encode qw(encode decode);
    
    while (<>) {
       # decode the utf-8 bytes and make them into characters
       # and turn anything that's invalid into U+FFFD
       my $string = decode("utf-8", $_);
    
       # change any U+FFFD into spaces
       $string =~ s/\x{fffd}/ /g;
    
       # turn it back into utf-8 bytes and print it back out again
       print encode("utf-8", $string);
    }
    

    或者更小的命令行版本:

    perl -pe 'use Encode; $_ = Encode::decode("utf-8",$_); s/\x{fffd}/ /g; $_ = Encode::encode("utf-8", $_)' 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-29
      • 2014-03-16
      • 1970-01-01
      • 2017-04-03
      • 2015-02-02
      • 2011-11-22
      • 2019-05-16
      • 1970-01-01
      相关资源
      最近更新 更多