2014-03-19 3 views
2

비 UTF8 문자가있는 고정 너비 파일이 있는데 비 UTF8 문자를 공백으로 대체하려고합니다.잘못된 UTF8 문자를 공백으로 바꾸는 방법

실행하려고 시도했지만 iconv -f utf8 -t utf8 -c $file 하지만 UTF8이 아닌 문자는 제거됩니다. iconv를 사용하여 공백으로 바꿀 방법이 없습니다.

utf8이 아닌 모든 문자를 공백으로 바꾸려면 korn 쉘 스크립트/perl 스크립트가 필요합니다.

비 utf8 문자가있는 행을 인쇄하는이 perl 스크립트를 발견했지만 non-UTF8을 공백으로 대체하도록 perl에 대해 알지 못합니다.

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

답변

2

펄의 인코딩 모듈은이 기능이 있습니다.

#!/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", $_)' 
관련 문제