user982570
user982570

Reputation: 251

How do I get a listing of only files using Dir.glob?

How can I return a list of only the files, not directories, in a specified directory?

I have my_list = Dir.glob(script_path.join("*"))

This returns everything in the directory,including subdirectories. I searched but haven't been able to find the answer.

Upvotes: 24

Views: 21940

Answers (8)

peter
peter

Reputation: 42192

Entries don't do rescursion i think. If you want the files in the subdirs also use

puts Dir['**/*'].select { |f| File.file?(f) }

Upvotes: 8

Erim Icel
Erim Icel

Reputation: 131

you can basically just get filenames with File.basename(file)

Dir.glob(script_path.join("*")).map{ |s| File.basename(s) }

Upvotes: 0

ReggieB
ReggieB

Reputation: 8212

Following @karl-li 's suggestion in @theIV solution, I found this to work well:

Dir.entries('path/to/files/folder').reject { |f| File.directory?(f) }

Upvotes: 3

karl li
karl li

Reputation: 1486

You can use Dir[]/Dir.glob or Dir.entries to get file listing. The difference between them is the former returns complete path, and the latter returns only filename.

So be careful about the following mapping segment .select {|f| File.file?(f)}: with complete path it works well, while with only filename, it sometimes works wired.

FYR:

Dir[], Dir.glob, Dir.entries

Upvotes: 1

Michael Kohl
Michael Kohl

Reputation: 66837

If you want to do it in one go instead of first creating an array and then iterating over it with select, you can do something like:

my_list = []
Dir.foreach(dir) { |f| my_list << f if File.file?(f) }

Upvotes: 4

theIV
theIV

Reputation: 25774

In addition to Mark's answer, Dir.entries will give back directories. If you just want the files, you can test each entry to see if it's a file or a directory, by using file?.

Dir.entries('/home/theiv').select { |f| File.file?(f) }

Replace /home/theiv with whatever directory you want to look for files in.

Also, have a look at File. It provides a bunch of tests and properties you can retrieve about files.

Upvotes: 32

Zepplock
Zepplock

Reputation: 29135

Dir.glob('*').select { |fn| File.file?(fn) }

Upvotes: 15

Mark Rushakoff
Mark Rushakoff

Reputation: 258188

It sounds like you're looking for Dir.entries:

Returns an array containing all of the filenames in the given directory. Will raise a SystemCallError if the named directory doesn’t exist.

If searching Google for how to solve this problem isn't turning up any results, you can look through the Ruby documentation.

Upvotes: -4

Related Questions