Skip to content

Instantly share code, notes, and snippets.

@z5h
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save z5h/a5dfd3b995022007893e to your computer and use it in GitHub Desktop.
Save z5h/a5dfd3b995022007893e to your computer and use it in GitHub Desktop.
does a join on 2 files based on 1st capture of regex. e.g.: join-on Gemfile "gem '([^']*)'" Gemfile.lock " *([^ ]*)"
#!/usr/bin/env ruby
# example use: join-on Gemfile "gem '([^']*)'" Gemfile.lock " *([^ ]*)"
file1, cap1, file2, cap2 = *ARGV
r1 = Regexp.new(cap1)
r2 = Regexp.new(cap2)
line_match_number = []
n = 0
max_len = 0
File.open(file1).each do |line|
match = r1.match(line)
n+=1
if match
line_match_number << [line, match[1], n]
max_len = [max_len, line.length].max
end
end
p1 = Math.log10(line_match_number.last[2]).to_i + 1
match_to_line_number = {}
n=0
File.open(file2).each do |line|
match = r2.match(line)
n+=1
if match
match_to_line_number[match[1]] = [line, n]
end
end
p2 = Math.log10(n).to_i + 1
line_match_number.each do |line, match, number|
if ln = match_to_line_number[match]
puts "#{number.to_s.rjust(p1)}|#{line[0...-1].ljust(max_len)}|#{ln[1].to_s.rjust(p2)}|#{ln[0]}"
else
puts "#{number.to_s.rjust(p1)}|#{line[0...-1].ljust(max_len)}|"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment