Skip to content

Instantly share code, notes, and snippets.

@stulentsev
Created April 4, 2014 16:36
Show Gist options
  • Save stulentsev/9978365 to your computer and use it in GitHub Desktop.
Save stulentsev/9978365 to your computer and use it in GitHub Desktop.
script to search yaml files
#! /usr/bin/env ruby
require 'yaml'
require 'colorize'
filename = ARGV[0]
pattern_text = ARGV[1]
unless filename && pattern_text
puts "Usage: grep_yaml.rb filename pattern"
exit(1)
end
pattern = Regexp.new(pattern_text, :nocase)
p pattern
hash = YAML.load_file(filename)
def recurse(obj, pattern, current_path = [], &block)
if obj.is_a?(String)
path = current_path.join('.')
if obj =~ pattern || path =~ pattern
yield [path, obj]
end
elsif obj.is_a?(Hash)
obj.each do |k, v|
recurse(v, pattern, current_path + [k], &block)
end
end
end
recurse(hash, pattern) do |path, value|
line = "#{path}:\t#{value}"
line = line.gsub(pattern) {|match| match.green }
puts line
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment