Last active
December 21, 2015 21:29
-
-
Save halferty/6368583 to your computer and use it in GitHub Desktop.
Ruby find in files
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 | |
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