CLOVER🍀

That was when it all began.

Linux上のコマンドで、ファイルの文字コードを変換する

これは、なにがしたくて書いたもの?

表題通り。iconvが有名だとは思いますが、ちゃんと使ってこなかったのでこの機会に、と。

環境

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.3 LTS
Release:    18.04
Codename:   bionic

iconv

有名どころですね。

基本的な使い方は、以下の通り。

$ iconv -f [from-encoding] -t [to-encoding] [input file]
$ iconv -f [from-encoding] -t [to-encoding] [input file] -o [output file]

iconvで使える、エンコーディングの一覧を取得する方法。

$ iconv -l

Shift_JISのファイルをUTF-8に変換し、標準出力に書き出す例。
※「hello_world_sjis.txt」は、Shift_JISで書かれたファイルです

$ iconv -f sjis -t utf-8 hello_world_sjis.txt
こんにちは、世界

Shift_JISのファイルをUTF-8に変換し、ファイルに書き出す例。

$ iconv -f sjis -t utf-8 hello_world_sjis.txt -o hello_world_utf8.txt

Perl One Liner

Encodeモジュールを使って、Perl One Linerでも。

$ perl -wp -MEncode -e 'Encode::from_to($_, "[from-encoding]", "[to-encoding]");' [input file] 
$ perl -wp -MEncode -e 'Encode::from_to($_, "[from-encoding]", "[to-encoding]");' [input file] > [output file]

Encodeモジュールで使える、エンコーディングの一覧を取得する方法。

$ perl -wl -MEncode -e 'print for Encode->encodings(":all")'

Shift_JISのファイルをUTF-8に変換し、標準出力に書き出す例。

$ perl -wp -MEncode -e 'Encode::from_to($_, "sjis", "utf-8");' hello_world_sjis.txt 
こんにちは、世界

Shift_JISのファイルをUTF-8に変換し、ファイルに書き出す例。

$ perl -wp -MEncode -e 'Encode::from_to($_, "sjis", "utf-8");' hello_world_sjis.txt > hello_world_utf8.txt

piconv

Perlが使える環境では、piconvというコマンドも使えます。ほぼ、iconvですね。

$ piconv -f [from-encoding] -t [to-encoding] [input file]
$ piconv -f [from-encoding] -t [to-encoding] [input file] > [output file]

piconvで使える、エンコーディングの一覧を取得する方法。

$ piconv -l

Shift_JISのファイルをUTF-8に変換し、標準出力に書き出す例。

$ piconv -f sjis -t utf-8 hello_world_sjis.txt
こんにちは、世界

Shift_JISのファイルをUTF-8に変換し、ファイルに書き出す例。

$ piconv -f sjis -t utf-8 hello_world_sjis.txt > hello_world_utf8.txt