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

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.directory? f}


답변

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

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

또는 디렉토리 File.file?가 아닌 모든 것 ( 비정규 파일을 거부 함) :

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

대체 솔루션

실제로 Find#find패턴 기반 조회 방법을 사용 하는 Dir.glob것이 더 좋습니다. “루비에서 디렉토리를 재귀 적으로 나열하는 한 줄짜리”에 대한이 답변을 참조하십시오. .


답변

이것은 나를 위해 작동합니다 :

숨겨진 파일을 원하지 않으면 [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유닉스에서 나는 Windows에 대해 모른다


답변

루비 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