programing

Ruby를 사용하여 폴더에서 모든 파일의 이름 가져오기

linuxpc 2023. 6. 5. 23:40
반응형

Ruby를 사용하여 폴더에서 모든 파일의 이름 가져오기

루비를 사용하여 모든 파일 이름을 폴더에서 가져오려고 합니다.

바로 가기 옵션도 있습니다.

Dir["/path/to/search/*"]

폴더 또는 하위 폴더에서 모든 Ruby 파일을 찾으려면 다음을 수행합니다.

Dir["/path/to/search/**/*.rb"]
Dir.entries(folder)

예:

Dir.entries(".")

출처: http://ruby-doc.org/core/classes/Dir.html#method-c-entries

다음 스니펫은 하위 디렉터리를 건너뛰고 디렉터리 안에 있는 파일의 이름을 정확하게 보여줍니다.".",".."점선 폴더:

Dir.entries("your/folder").select { |f| File.file? File.join("your/folder", f) }

모든 파일(엄격한 파일만)을 재귀적으로 가져오려면:

Dir.glob('path/**/*').select { |e| File.file? e }

디렉토리가 것은 File.file?비정규 파일을 거부합니다):

Dir.glob('path/**/*').reject { |e| File.directory? e }

대체 솔루션

다음과 같은 패턴 기반 조회 방법 사용Dir.glob사실은 더 낫습니다."Ruby의 디렉토리를 재귀적으로 나열하는 단일 라이너?"에 대한 다음 답변을 참조하십시오.

이것은 나에게 도움이 됩니다.

숨겨진 파일[1]을(를) 원하지 않으면 Dir[]:

# With a relative path, Dir[] will return relative paths 
# as `[ './myfile', ... ]`
#
Dir[ './*' ].select{ |f| File.file? f } 

# Want just the filename?
# as: [ 'myfile', ... ]
#
Dir[ '../*' ].select{ |f| File.file? f }.map{ |f| File.basename f }

# Turn them into absolute paths?
# [ '/path/to/myfile', ... ]
#
Dir[ '../*' ].select{ |f| File.file? f }.map{ |f| File.absolute_path f }

# With an absolute path, Dir[] will return absolute paths:
# as: [ '/home/../home/test/myfile', ... ]
#
Dir[ '/home/../home/test/*' ].select{ |f| File.file? f }

# Need the paths to be canonical?
# as: [ '/home/test/myfile', ... ]
#
Dir[ '/home/../home/test/*' ].select{ |f| File.file? f }.map{ |f| File.expand_path f }

이제 Dir.entries는 숨겨진 파일을 반환하며 와일드카드 별표(디렉토리 이름으로 변수를 전달하기만 하면 됨)는 필요하지 않지만 기본 이름을 직접 반환하므로 File(파일)이 반환됩니다.xxx 함수가 작동하지 않습니다.

# In the current working dir:
#
Dir.entries( '.' ).select{ |f| File.file? f }

# In another directory, relative or otherwise, you need to transform the path 
# so it is either absolute, or relative to the current working dir to call File.xxx functions:
#
home = "/home/test"
Dir.entries( home ).select{ |f| File.file? File.join( home, f ) }

[1].dotfile에 대해 잘 .

2 Ruby 2.5를 사용할 수 .Dir.children및를 한 파일 . "...를 제외한 파일 이름을 배열로 가져옵니다."

예:

Dir.children("testdir")   #=> ["config.h", "main.rb"]

http://ruby-doc.org/core-2.5.0/Dir.html#method-c-children

개인적으로, 저는 이것이 폴더의 파일을 루프오버하고 미래의 안전을 보장하는 데 가장 유용하다는 것을 알게 되었습니다.

Dir['/etc/path/*'].each do |file_name|
  next if File.directory? file_name 
end

다음은 디렉터리에서 파일을 찾는 방법입니다.

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

이 코드는 확장자가 있는 파일 이름만 반환합니다(글로벌 경로 없음).

Dir.children("/path/to/search/")

=> [file_1.dll, file_2.dll, file_3.js]

파일 이두 모두를 하는 데 될 수 [Discription]..,.. ]로 및 [ ]로 시작하는 히든파일.

files = Dir.entries("your/folder").reject {|f| File.directory?(f) || f[0].include?('.')}

이것이 제게 맞는 일입니다.

Dir.entries(dir).select { |f| File.file?(File.join(dir, f)) }

Dir.entries문자열 배열을 반환합니다. 다음,의 전체 경로를 다전경제합니다야공해로를그에 .File.file?,~하지 않는 한dir현재 작업 디렉토리와 동일합니다.이 그서이게래.File.join().

Dir.new('/home/user/foldername').each { |file| puts file }

여러분은 사할수있다니습을 사용하는 .Rake::FileList (으)ㄹ게요)rake종속성):

FileList.new('lib/*') do |file|
  p file
end

API에 따르면:

파일 목록은 게으릅니다.파일 목록에 포함될 가능성이 있는 파일에 대한 글로벌 패턴 목록이 지정되면 파일 구조를 검색하여 파일을 찾는 대신 FileList는 나중에 사용할 수 있도록 패턴을 유지합니다.

https://docs.ruby-lang.org/en/2.1.0/Rake/FileList.html

한 가지 간단한 방법은 다음과 같습니다.

dir = './' # desired directory
files = Dir.glob(File.join(dir, '**', '*')).select{|file| File.file?(file)}

files.each do |f|
    puts f
end
def get_path_content(dir)
  queue = Queue.new
  result = []
  queue << dir
  until queue.empty?
    current = queue.pop
    Dir.entries(current).each { |file|
      full_name = File.join(current, file)
      if not (File.directory? full_name)
        result << full_name
      elsif file != '.' and file != '..'
          queue << full_name
      end
    }
  end
  result
end

디렉터리 및 모든 하위 디렉터리에서 파일의 상대 경로를 반환합니다.

심볼릭 링크를 포함한 파일 이름 배열을 가져오려면

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

아니 심지어는

Dir.new('/path/to/dir').reject { |f| File.directory? f }

그리고 심볼릭 링크 없이 가고 싶다면,

Dir.new('/path/to/dir').select { |f| File.file? f }

다른 답변에 표시된 것처럼 다음을 사용합니다.Dir.glob('/path/to/dir/**/*')대신에Dir.new('/path/to/dir')모든 파일을 재귀적으로 가져오려는 경우.

이 스레드의 제안 외에도 Dir.glob과 함께 도트 파일(.gitignore 등)을 반환해야 한다면 플래그를 포함해야 한다는 점을 언급하고 싶습니다.Dir.glob("/path/to/dir/*", File::FNM_DOTMATCH)기본적으로 Dir.entries에는 도트 파일과 현재 상위 디렉터리가 포함됩니다.

관심이 있는 사람이라면 실행 시간에 대한 여기의 답변이 서로 어떻게 비교되는지 궁금했습니다. 여기 깊이 중첩된 계층 구조에 대한 결과가 있습니다.처음 세 가지 결과는 비재귀적입니다.

       user     system      total        real
Dir[*]: (34900 files stepped over 100 iterations)
  0.110729   0.139060   0.249789 (  0.249961)
Dir.glob(*): (34900 files stepped over 100 iterations)
  0.112104   0.142498   0.254602 (  0.254902)
Dir.entries(): (35600 files stepped over 100 iterations)
  0.142441   0.149306   0.291747 (  0.291998)
Dir[**/*]: (2211600 files stepped over 100 iterations)
  9.399860  15.802976  25.202836 ( 25.250166)
Dir.glob(**/*): (2211600 files stepped over 100 iterations)
  9.335318  15.657782  24.993100 ( 25.006243)
Dir.entries() recursive walk: (2705500 files stepped over 100 iterations)
 14.653018  18.602017  33.255035 ( 33.268056)
Dir.glob(**/*, File::FNM_DOTMATCH): (2705500 files stepped over 100 iterations)
 12.178823  19.577409  31.756232 ( 31.767093)

이들은 다음과 같은 벤치마킹 스크립트를 사용하여 생성되었습니다.

require 'benchmark'
base_dir = "/path/to/dir/"
n = 100
Benchmark.bm do |x|
  x.report("Dir[*]:") do
    i = 0
    n.times do
      i = i + Dir["#{base_dir}*"].select {|f| !File.directory? f}.length
    end
    puts " (#{i} files stepped over #{n} iterations)"
  end
  x.report("Dir.glob(*):") do
    i = 0
    n.times do
      i = i + Dir.glob("#{base_dir}/*").select {|f| !File.directory? f}.length
    end
    puts " (#{i} files stepped over #{n} iterations)"
  end
  x.report("Dir.entries():") do
    i = 0
    n.times do
      i = i + Dir.entries(base_dir).select {|f| !File.directory? File.join(base_dir, f)}.length
    end
    puts " (#{i} files stepped over #{n} iterations)"
  end
  x.report("Dir[**/*]:") do
    i = 0
    n.times do
      i = i + Dir["#{base_dir}**/*"].select {|f| !File.directory? f}.length
    end
    puts " (#{i} files stepped over #{n} iterations)"
  end
  x.report("Dir.glob(**/*):") do
    i = 0
    n.times do
      i = i + Dir.glob("#{base_dir}**/*").select {|f| !File.directory? f}.length
    end
    puts " (#{i} files stepped over #{n} iterations)"
  end
  x.report("Dir.entries() recursive walk:") do
    i = 0
    n.times do
      def walk_dir(dir, result)
        Dir.entries(dir).each do |file|
          next if file == ".." || file == "."

          path = File.join(dir, file)
          if Dir.exist?(path)
            walk_dir(path, result)
          else
            result << file
          end
        end
      end
      result = Array.new
      walk_dir(base_dir, result)
      i = i + result.length
    end
    puts " (#{i} files stepped over #{n} iterations)"
  end
  x.report("Dir.glob(**/*, File::FNM_DOTMATCH):") do
    i = 0
    n.times do
      i = i + Dir.glob("#{base_dir}**/*", File::FNM_DOTMATCH).select {|f| !File.directory? f}.length
    end
    puts " (#{i} files stepped over #{n} iterations)"
  end
end

파일 수의 차이는 다음과 같습니다.Dir.entries기본적으로 숨김 파일을 포함합니다. Dir.entries이 경우 파일이 디렉터리인지 확인하기 위해 파일의 절대 경로를 다시 작성해야 하기 때문에 시간이 좀 더 오래 걸렸지만, 파일이 없는 경우에도 재귀적인 경우의 다른 옵션보다 지속적으로 더 오래 걸렸습니다.이는 모두 OSX에서 루비 2.5.1을 사용한 것입니다.

운영 디렉토리에 있는 모든 파일 이름을 로드할 때 사용할 수 있습니다.

Dir.glob("*)

이렇게 하면 응용프로그램이 실행 중인 컨텍스트 내의 모든 파일이 반환됩니다(Rails의 경우 이 디렉토리는 응용프로그램의 최상위 디렉토리입니다)

https://ruby-doc.org/core-2.7.1/Dir.html#method-c-glob 에서 추가 일치 및 재귀 검색을 수행할 수 있습니다.

공백이 있는 디렉터리를 만드는 경우:

mkdir "a b"
touch "a b/c"

디렉토리 이름을 이스케이프할 필요가 없습니다. 디렉토리 이름은 자동으로 실행됩니다.

p Dir["a b/*"] # => ["a b/c"]

언급URL : https://stackoverflow.com/questions/1755665/get-names-of-all-files-from-a-folder-with-ruby

반응형