Ruby: how do I recursively find and remove empty d

2020-06-16 02:26发布

I'm trying to write some ruby that would recursively search a given directory for all empty child directories and remove them.

Thoughts?

Note: I'd like a script version if possible. This is both a practical need and a something to help me learn.

标签: ruby file
9条回答
可以哭但决不认输i
2楼-- · 2020-06-16 02:55
Dir['/Users/path/Movies/incompleteAnime/foom/**/*']. \
select { |d| File.directory? d }. \
sort.reverse. \
each {|d| Dir.rmdir(d) if Dir.entries(d).size ==  2}

just like the first example, but the first example doesn't seem to handle the recursive bit. The sort and reverse ensures we deal with the most nested directories first.

I suppose sort.reverse could be written as sort {|a,b| b <=> a} for efficiency

查看更多
姐就是有狂的资本
3楼-- · 2020-06-16 02:59

Looking at the examples from kch, dB. and Vishnu above, I've put together a one-liner that I think is a more elegant solution:

Dir['**/'].reverse_each { |d| Dir.rmdir d if Dir.entries(d).size == 2 }

I use '**/' instead of '/**/*' for the glob, which only returns directories, so I don't have to test whether it's a directory later. I'm using reverse_each instead of sort.reverse.each as it's shorter and supposedly more efficient, according to this post. I prefer Dir.entries(d).size == 2 to (Dir.entries(d) - %w[ . .. ]).empty? because it's a little easier to read and understand, although (Dir.entries(d) - %w[ . .. ]).empty? would probably work better if you had to run your script on Windows.

I've tested this quite a bit on Mac OS X and it works well, even with recursive empty directories.

查看更多
Fickle 薄情
4楼-- · 2020-06-16 03:00

In ruby:

Dir['**/*']                                            \
  .select { |d| File.directory? d }                    \
  .select { |d| (Dir.entries(d) - %w[ . .. ]).empty? } \
  .each   { |d| Dir.rmdir d }
查看更多
登录 后发表回答