Hi folks. Today I had to write script that would delete all the empty directories in a directory tree recursively. Ie, removing any empty leaf dirs, and then moving up and removing the next layer if it is now empty, etc.
I thought that there must be a nice neat compact perlish way to do this, but it seemed to elude me. Anyway, the code I came up with is below, I'm wondering how compact this can be golfed down to by the folks out there that are good at golf. Requirements are to take a list of root dirs on the command line, delete any empty dirs, and then print out the number of dirs removed and the number kept. Ill accept anything that matches /D:\d+\s+F:\d+/ as the output string. It should die if there any errors removing the dirs, and the code need not worry about circular directories due to symlinks or the like. Have fun. :-) (You can assume there are no hidden or system files lurking in the tree, thanks davis for raising this issue.)
use strict; use warnings; use File::Find; use Cwd; my $deleted=0; my $keep=0; $|++; sub recurse { my $dir=shift; chdir $dir or die "chdir $dir:$!"; my $dirname=cwd; #print "$dirname\n"; my @dirs; my @files; for my $name (glob '*') { next unless $name=~/[^.]/; if (-d $name) { push @dirs,$name if recurse($name); } else { push @files,$name; } } chdir ".."; unless (@dirs or @files) { print "X: $dirname\n"; rmdir $dir or warn "$dirname:$!"; $deleted++; } else { print "k: $dirname (d: " . scalar(@dirs) . " | f: ".scalar(@files).")\n"; $keep++; } return @dirs+@files; } recurse $_ for @ARGV; print "Deleted $deleted directories, kept $keep directories\n";
First they ignore you, then they laugh at you, then they fight you, then you win.
-- Gandhi
In reply to (golf) Recursively delete empty directories from a tree by demerphq
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |