On Sep 13, 2013, at 11:30 AM, amanda honey [email protected] wrote:
Searching for string
–
Posted via http://www.ruby-forum.com/.
The way you’ve called Dir.glob, it can easily return directories as well
as plain files. Joel’s response is a good one, but it can still return
terminal directories that are empty.
Even doing Dir[‘**/*’] will get you more than you bargained for.
Example: set up a quick demo:
tamara@pontiki:~:2013-09-13@07:07:42
$ cd /tmp
tamara@pontiki:/tmp:2013-09-13@09:37:29
$ mkdir -p test/recursive/dirs.ext
tamara@pontiki:/tmp:2013-09-13@09:37:50
$ ls -al test
total 0
drwxr-xr-x 3 tamara wheel 102B Sep 13 21:37 ./
drwxrwxrwt 17 root wheel 578B Sep 13 21:37 …/
drwxr-xr-x 3 tamara wheel 102B Sep 13 21:37 recursive/
tamara@pontiki:/tmp:2013-09-13@09:38:02
$ ls -alR test
total 0
drwxr-xr-x 3 tamara wheel 102B Sep 13 21:37 ./
drwxrwxrwt 17 root wheel 578B Sep 13 21:37 …/
drwxr-xr-x 3 tamara wheel 102B Sep 13 21:37 recursive/
test/recursive:
total 0
drwxr-xr-x 3 tamara wheel 102B Sep 13 21:37 ./
drwxr-xr-x 3 tamara wheel 102B Sep 13 21:37 …/
drwxr-xr-x 2 tamara wheel 68B Sep 13 21:37 dirs.ext/
test/recursive/dirs.ext:
total 0
drwxr-xr-x 2 tamara wheel 68B Sep 13 21:37 ./
drwxr-xr-x 3 tamara wheel 102B Sep 13 21:37 …/
tamara@pontiki:/tmp:2013-09-13@09:38:13
$ touch test/recursive/file
tamara@pontiki:/tmp:2013-09-13@09:39:34
$ touch test/recursive/file_with.ext
Then:
[104] pry(main)> Dir[‘/tmp/test//*‘].inject({}){|m,o|
m[o]=File.ftype(o);m}
=> {“/tmp/test/recursive”=>“directory”,
“/tmp/test/recursive/dirs.ext”=>“directory”,
“/tmp/test/recursive/file”=>“file”,
“/tmp/test/recursive/file_with.ext”=>“file”}
[105] pry(main)> Dir[’/tmp/test//.’].inject({}){|m,o|
m[o]=File.ftype(o);m}
=> {“/tmp/test/recursive/dirs.ext”=>“directory”,
“/tmp/test/recursive/file_with.ext”=>“file”}
[106] pry(main)>
So in your code, it will fail if you try IO.foreach on a directory
A simple enough rewrite:
def grep_r(search_criteria, starting_directory=‘.’)
raise “Search criteria must be a regular expression” unless
search_criteria.kind_of? Regexp
raise “Starting point not a directory” unless File.directory?
starting_directory
Dir[FIle.join(starting_directory,“**”,“*”)].each do |entry|
next unless FIle.ftype(entry) == “file”
IO.foreach(entry) do |line|
if line =~ str
puts "#{filename}: #{line} "
puts “--------------------------------------------------”
# logger = Logger.new($stdout) # ← this is useless, you’re not
doing anything with this, and setting it each time through the loop is a
waste
end # if
end # IO.foreach
end # Dir…each
end
grep_r(%r{some|set|of|words|to|find}, ‘.’)
grep_r(%r{someother|set|of|words to
find},File.join(ENV[‘HOME’],‘Documents’,“ThatImportantProject”))