Skip to content

Instantly share code, notes, and snippets.

@xiaohanyu
Created February 22, 2014 11:23
Show Gist options
  • Save xiaohanyu/9152330 to your computer and use it in GitHub Desktop.
Save xiaohanyu/9152330 to your computer and use it in GitHub Desktop.
Convert file encoding
#!/usr/bin/env ruby
require 'optparse'
require 'pry'
def main
options = {to_encoding: 'utf-8'}
option_parser = OptionParser.new do |opts|
executable_name = File.basename($PROGRAM_NAME)
opts.banner = "Convert file from one encoding to another
Usage: #{executable_name} [options] input_filename output_filename"
opts.on("-f from-encoding") do |from_encoding|
options[:from_encoding] = from_encoding
end
opts.on("-t to-encoding") do |to_encoding|
options[:to_encoding] = to_encoding
end
end
option_parser.parse!
input_filename = ARGV.shift
output_filename = ARGV.shift
output_file = File.open(output_filename, 'a')
File.open(input_filename) do |file|
file.each_line do |line|
output_file << line.encode(options[:to_encoding],
options[:from_encoding])
end
end
end
if __FILE__ == $0
main
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment