iconv で変換できない不正な文字を除外するには -c オプションを使えばいい

Linux 上でデータベースから出力した CSV ファイルの文字コードを UTF-8 から Shift JIS に変換しようとしたら、変換できない文字が含まれていたみたいで illegal input sequence at position というエラーが発生して処理途中で終了してしまいました。

Linux | リナックス

$ iconv -f utf-8 -t sjis -o output-sjis.csv input.csv
iconv: illegal input sequence at position 652782

-c オプションをつけると処理が途中で止まることなく、不正な文字を出力から除外して最後まで処理してくれます。

$ iconv -c -f utf-8 -t sjis -o output-sjis.csv input.csv

ヘルプにちゃんと記載されてました。

$ iconv --help
Usage: iconv [OPTION...] [FILE...]
Convert encoding of given files from one encoding to another.
 
 Input/Output format specification:
  -f, --from-code=NAME       encoding of original text
  -t, --to-code=NAME         encoding for output
 
 Information:
  -l, --list                 list all known coded character sets
 
 Output control:
  -c                         omit invalid characters from output
  -o, --output=FILE          output file
  -s, --silent               suppress warnings
      --verbose              print progress information
 
  -?, --help                 Give this help list
      --usage                Give a short usage message
  -V, --version              Print program version
 
Mandatory or optional arguments to long options are also mandatory or optional
for any corresponding short options.
 
For bug reporting instructions, please see:
<http://www.gnu.org/software/libc/bugs.html>.

CSV ファイルを Excel で開くために Shift JIS に変換するなんて作業からは、そろそろ卒業したい気分です。