シナリオ
Windows上(cp932)でファイル名「ラインハルトの旗艦.txt」を「text.zip」という名前で圧縮し、Linux(utf8)上にて展開する。
unzipで解凍
オプションなしでunzipを実行するとファイル名が文字化けする。
$ unzip text.zip
Archive: text.zip
extracting: text/ГЙГCГУГnГЛГgВtК°Кq.txt
-I、-Oオプションでunzipを実行するとファイル名がutf8に変換される
$ unzip -I utf8 -O cp932 text.zip
Archive: text.zip
extracting: text/ラインハルトの旗艦.txt
オプションの意味は以下。unzip --help(UnZip 6.00 of 20 April 2009)より。
-O CHARSET specify a character encoding for DOS, Windows and OS/2 archives
-I CHARSET specify a character encoding for UNIX and other archives
ファイルの文字コード変換
上記の方法では、ファイルの中身はUTF8に変換されない。
$ cat text/ラインハルトの旗艦.txt
u
q
g
iconvにてファイルの内部をutf8に変換する。
$ iconv -f cp932 -t UTF-8 ラインハルトの旗艦.txt
ブリュンヒルト
上記では標準出力となるが、-oオプションでファイルへ上書き保存もできる。
$ iconv -f cp932 -t UTF-8 ラインハルトの旗艦.txt -o ラインハルトの旗艦.txt
$ cat ラインハルトの旗艦.txt
ブリュンヒルト
改行コードの変換
さらに改行コードがCRLFの場合はLFに変更する必要がある。
$ file ラインハルトの旗艦.txt
ラインハルトの旗艦.txt: UTF-8 Unicode text, with CRLF line terminators
いろいろ方法があるが以下ではsedで変換する方法。
$ sed -i -e 's/\r//g' ラインハルトの旗艦.txt
$ file ラインハルトの旗艦.txt
ラインハルトの旗艦.txt: UTF-8 Unicode text