Skip to content

Instantly share code, notes, and snippets.

@mhjb
Last active December 16, 2015 09:18
Show Gist options
  • Save mhjb/5411520 to your computer and use it in GitHub Desktop.
Save mhjb/5411520 to your computer and use it in GitHub Desktop.
Combine ranges in book index
def combine_nums(line)
line.gsub!(/(\d+), (?=(\d+))/) { # combine consecutive & identical numbers
if $2.to_i - $1.to_i == 1 # (looks-ahead so as to check
"#{$1}-" # every set of two numbers)
elsif $2.to_i == $1.to_i
""
else
"#{$1}, "
end
}
line.gsub!(/-(\d+), (\d+)/) { # remove numbers after ranges included in same
if $2.to_i < $1.to_i
"-#{$1}"
else
"#{$&}"
end
}
line.gsub!(/(\d+)-(\d+-)+(\d+)/) { "#{$1}-#{$3}" } # remove inner numbers from ranges
line.gsub!(/(\d)(\d\d)-\1(\d\d)/) { "#{$1}#{$2}-#{$3}"} # make e.g. 323-343 into 323-43
line.gsub!(/(\d0\d)-0(\d)/) { "#{$1}-#{$2}"} # make e.g. 306-08 into 306-8
return line
end
if ARGV.empty?
puts "Please supply a filename, or --clipboard"
elsif ARGV[0] == "--clipboard"
require 'clipboard'
clipout = []
Clipboard.paste.split("\r").each { |line| clipout << combine_nums(line) }
Clipboard.copy(clipout.join("\r"))
else
File.open(ARGV[0]).each(sep="\r") do |line| # Mac classic newlines
puts combine_nums(line)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment