Get names of all files from a folder with Ruby

后端 未结 19 2195
[愿得一人]
[愿得一人] 2020-11-29 14:57

I want to get all file names from a folder using Ruby.

相关标签:
19条回答
  • 2020-11-29 15:42

    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().

    0 讨论(0)
  • 2020-11-29 15:43

    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

    0 讨论(0)
  • 2020-11-29 15:44

    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
    
    0 讨论(0)
  • 2020-11-29 15:47

    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?('.')}
    
    0 讨论(0)
  • 2020-11-29 15:48

    this code returns only filenames with their extension (without a global path)

    Dir.children("/path/to/search/")
    
    0 讨论(0)
  • 2020-11-29 15:51

    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) }
    
    0 讨论(0)
提交回复
热议问题