3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby でディレクトリ以下のファイルを再帰的に探索する

Posted at

概要

  • Ruby でディレクトリ以下のファイルを再帰的に探索するプログラムを書く
  • Dir.glob と Dir#children を使ったパターンを示す

動作確認用のディレクトリとファイルを用意

$ tree -a sample/
sample/
├── .a.config
├── a.jpg
├── a.txt
└── dir1
    ├── .b.config
    ├── b.jpg
    ├── b.txt
    └── dir2
        ├── .c.config
        ├── c.jpg
        └── c.txt

2 directories, 9 files

Dir.glob を使うパターン

ソースコード。
FNM_DOTMATCH フラグで先頭のドット「.」にもマッチさせている。

# 第1引数をターゲットのディレクトリパスとする
# 未指定の場合はカレントディレクトリを指定する
target_dir = ARGV.length > 0 ? ARGV[0] : '.'
puts "target_dir: #{target_dir}"

# ディレクトリを再帰的に辿る
Dir.glob('**/*', File::FNM_DOTMATCH, base: target_dir).each do |file|
  # ファイルのパスを作る
  file_path = File.join(target_dir, file)
  puts "#{file_path}"
end

実行結果。

$ ruby dir_glob.rb sample/
target_dir: sample/
sample/.
sample/.a.config
sample/a.txt
sample/dir1
sample/dir1/.
sample/dir1/dir2
sample/dir1/dir2/.
sample/dir1/dir2/.c.config
sample/dir1/dir2/c.txt
sample/dir1/dir2/c.jpg
sample/dir1/b.txt
sample/dir1/b.jpg
sample/dir1/.b.config
sample/a.jpg

Dir#children を使うパターン

ソースコード。

# 再帰的にディレクトリ内のファイルを調べる
def recursive_search(dir_path)

  dir = Dir.new(dir_path)

  # "." と ".." を除いたファイル名の配列でループ
  dir.children.each do |file_name|

    # ディレクトリのパスとファイル名からファイルのパスを作る
    file_path = File.join(dir_path, file_name)
    puts "#{file_path}"

    # ファイルがディレクトリだったら再帰的に関数を呼び出す
    if File.directory?(file_path)
      recursive_search(file_path)
    end
  end
end

# 第1引数をターゲットのディレクトリパスとする
# 未指定の場合はカレントディレクトリを指定する
target_dir = ARGV.length > 0 ? ARGV[0] : '.'
puts "target_dir: #{target_dir}"

recursive_search(target_dir)

実行結果。

$ ruby dir_children.rb sample/
target_dir: sample/
sample/.a.config
sample/a.txt
sample/dir1
sample/dir1/dir2
sample/dir1/dir2/.c.config
sample/dir1/dir2/c.txt
sample/dir1/dir2/c.jpg
sample/dir1/b.txt
sample/dir1/b.jpg
sample/dir1/.b.config
sample/a.jpg

今回の動作確認環境

  • macOS Mojave
  • Ruby 2.6.4

参考資料

3
2
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?