#!/usr/bin/ruby
# orders the targets
# reads the file twice, uses just a little memory
# Urs Meyer, ursmr [at] gmx.ch, September 2008
filename = ARGV[0] || "sample4.txt"
# pass 1: collect footnote targets, map to new reference numbers
mapping = {}
newref = 0
File.open(filename).each_line { |line|
# start processing after marker line
unless ($. == 1) .. line =~ /@footnote:/
line =~ /\[(\d+)\]/
mapping[$1] = (newref += 1) unless $1.nil?
end
}
# pass 2: substitute footnote references
File.open(filename).each_line { |line|
puts line.gsub(/\[(\d+)\]/) { "[#{mapping[$1]}]" }
}