文字化けしたUTF8の変換

よくある\u30e1みたいに16進になってしまったUTF8の変換

#!/usr/bin/env ruby
# -*- mode: ruby; coding: utf-8 -*-

require 'optparse'

def main
  prefix = '\u'
  suffix = ''
  
  parser = OptionParser.new
  parser.banner = "Usage: #{File.basename($0)} [options]"
  parser.on('--suffix=SUFFIX',String, 'Suffix of raw unicode.') do |s|
    suffix = s
  end
  parser.on('--prefix=SUFFIX',String, 'Prefix of raw unicode.') do |p|
    prefix = p
  end
  parser.on('--help', 'Prints this message and quit.') do
    puts parser.help
    exit 0
  end

  begin
    parser.parse!
  rescue OptionParser::ParseError => err
    $stderr.puts err.message
    $stderr.puts parser.help
    exit 1
  end
  raw_unicode_re = /#{Regexp.quote(prefix)}([0-9a-fA-f]{0,4})#{Regexp.quote(suffix)}/ 

  unless ARGV.length > 0
    $stderr.puts parser.help
    exit(0)
  end
  
  File.open(ARGV[0], "r") do |file|
    file.each_line do |l|
      puts l.gsub(raw_unicode_re) { 
        [$1.hex].pack("U")
      }
    end
  end

end

main

追記

あとから気づいたけど、これってjavaのnative2asciiの逆をしているだけだった。