Skip to content

Instantly share code, notes, and snippets.

@halferty
Last active December 21, 2015 21:29
Show Gist options
  • Save halferty/6368583 to your computer and use it in GitHub Desktop.
Save halferty/6368583 to your computer and use it in GitHub Desktop.
Ruby find in files
#!/usr/bin/ruby
TOTAL_COLS = `tput cols`
FILENAME_WIDTH = 70
LINENUM_WIDTH = 5
TEXTSAMPLE_WIDTH = TOTAL_COLS.to_i - 90
search = ARGV[0]
if search
puts "Searching for #{search} in #{Dir.pwd}."
files = Dir["**/*"].reject { |f| File.directory? f }
files.each do |f|
begin
File.readlines(f).select { |line| line.include? search }.each_with_index do |l, i|
puts "#{f[0, FILENAME_WIDTH].rjust FILENAME_WIDTH, ' '} @ line #{i.to_s.rjust LINENUM_WIDTH, ' '}: #{l[0, TEXTSAMPLE_WIDTH]}"
end
rescue
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment