2

I'm trying to search for a certain file type within all directories on my unix system using a ruby script. I understand the following code will search all files ending with .pdf within the current directory:

my_pdfs = Dir['*pdf']

As well as:

my_pdfs = Dir.glob('*.pdf').each do |f|
  puts f
end

But how about searching all directories and sub-directories for files with the .pdf extension?

Mur Quirk
  • 171
  • 1
  • 2
  • 12
  • possible duplicate of [Searching a folder and all of its subfolders for files of a certain type](http://stackoverflow.com/questions/3498539/searching-a-folder-and-all-of-its-subfolders-for-files-of-a-certain-type) – Matt Mar 21 '12 at 01:54
  • @Matt I actually tried to use the solution there but got the following syntax error: syntax error, unexpected '=' My first assumption was that i was using ruby 1.9.3 and that was posted in 2010 so it was an earlier version of ruby? – Mur Quirk Mar 21 '12 at 02:04
  • @MurQuirk What line of that did you get the syntax error on? Perhaps you should comment there with your problem with it? – Andrew Marshall Mar 21 '12 at 02:36
  • For those who had problems with the solution on [Searching a folder and all of its subfolders for files of a certain type](http://stackoverflow.com/questions/3498539/searching-a-folder-and-all-of-its-subfolders-for-files-of-a-certain-type), on line 5 of the code the tilde goes after the equal operator, not before. So instead of `~=` its `=~` This probably shouldn't be posted here, but once I get 50 rep points I'll go ahead and comment on it over there. – Mur Quirk Mar 21 '12 at 23:41

2 Answers2

4

Check out the Find module: http://www.ruby-doc.org/stdlib-1.9.3/libdoc/find/rdoc/Find.html

Using Dir.glob is less than ideal since globbing doesn't handle recursion nearly as well as something like find.

Also if you're on a *nix box try using the find command. Its pretty amazingly useful for one liners.

Kyle
  • 735
  • 1
  • 5
  • 16
1

Maybe something like:

pdfs=Dir['/**/*.pdf']

?

Not using Linux right now, so don't know if that will work. The ** syntax implies recursive listing.

itdoesntwork
  • 4,666
  • 3
  • 25
  • 38