Created
February 22, 2014 11:23
-
-
Save xiaohanyu/9152330 to your computer and use it in GitHub Desktop.
Convert file encoding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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