Last active
December 20, 2018 01:40
-
-
Save compwron/77b4ad3af2c04ab44e9de41ed122215f to your computer and use it in GitHub Desktop.
Find the line number of a key in a long yaml file
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/ruby | |
# frozen_string_literal: true | |
require 'yaml' | |
to_find = ARGV[0] | |
puts "Finding #{to_find}" | |
parts = to_find.split('.') | |
filename = 'config/locales/en.yml' | |
lines = File.readlines(filename) | |
current_lines_with_index = lines.each_with_index.to_a | |
current_base_idx = 0 | |
current_indentation = -2 | |
begin | |
parts.each do |next_part| | |
next_line = current_lines_with_index.select do |line, idx| | |
line.strip.split(':').first == next_part && idx > current_base_idx | |
end.reject do |line, _idx| | |
indentation = line[/\A */].size | |
indentation != current_indentation + 2 | |
end.min_by do |_, idx| | |
idx | |
end | |
current_base_idx = next_line.last | |
current_indentation = next_line.first[/\A */].size | |
puts "#{next_part}: #{current_base_idx}" | |
end | |
puts "#{to_find} found at #{current_base_idx + 1}" | |
rescue | |
puts "Could not find #{to_find}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment