Created
April 22, 2014 06:48
-
-
Save rahult/11167689 to your computer and use it in GitHub Desktop.
Parameterize text
This file contains hidden or 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/ruby | |
def parameterize(string, sep = '-') | |
# Turn unwanted chars into the separator | |
string.gsub!(/[^a-z0-9\-_]+/i, sep) | |
unless sep.nil? || sep.empty? | |
re_sep = Regexp.escape(sep) | |
# No more than one of the separator in a row. | |
string.gsub!(/#{re_sep}{2,}/, sep) | |
# Remove leading/trailing separator. | |
string.gsub!(/^#{re_sep}|#{re_sep}$/i, '') | |
end | |
string.downcase | |
end | |
if ARGV.length < 2 | |
puts "" | |
puts "Please specify infile and outfile" | |
puts "" | |
puts "eg. #{$0} infile.txt outfile.txt" | |
puts "" | |
exit | |
end | |
infile_path = File.expand_path(ARGV[0]) | |
outfile_path = File.expand_path(ARGV[1]) | |
File.open(outfile_path, 'w') do |outfile| | |
File.open(infile_path, 'r').each do |line| | |
parameterized_line = parameterize(line) | |
puts "#{parameterized_line}" | |
outfile.puts parameterize(line) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment