I want to get all file names from a folder using Ruby.
This is what works for me:
Dir.entries(dir).select { |f| File.file?(File.join(dir, f)) }
Dir.entries
returns an array of strings. Then, we have to provide a full path of the file to File.file?
, unless dir
is equal to our current working directory. That's why this File.join()
.
You may also want to use Rake::FileList
(provided you have rake
dependency):
FileList.new('lib/*') do |file|
p file
end
According to the API:
FileLists are lazy. When given a list of glob patterns for possible files to be included in the file list, instead of searching the file structures to find the files, a FileList holds the pattern for latter use.
https://docs.ruby-lang.org/en/2.1.0/Rake/FileList.html
This is a solution to find files in a directory:
files = Dir["/work/myfolder/**/*.txt"]
files.each do |file_name|
if !File.directory? file_name
puts file_name
File.open(file_name) do |file|
file.each_line do |line|
if line =~ /banco1/
puts "Found: #{line}"
end
end
end
end
end
While getting all the file names in a directory, this snippet can be used to reject both directories [.
, ..
] and hidden files which start with a .
files = Dir.entries("your/folder").reject {|f| File.directory?(f) || f[0].include?('.')}
this code returns only filenames with their extension (without a global path)
Dir.children("/path/to/search/")
The following snippets exactly shows the name of the files inside a directory, skipping subdirectories and "."
, ".."
dotted folders:
Dir.entries("your/folder").select { |f| File.file? File.join("your/folder", f) }