Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Remove eMpTy Directories

by tye (Sage)
on Nov 18, 2002 at 16:45 UTC ( [id://213798]=sourcecode: print w/replies, xml ) Need Help??
Category: Utility Scripts
Author/Contact Info tye
Description: Traverses a directory tree deleting any directories that are empty or only contain subdirectories that get deleted.

Updated.

#!/usr/bin/perl -w

use strict;

exit(  main( @ARGV )  );

sub DIR() { 1 }
sub FILE() { 2 }

sub dropEmpty {
    my( $parent, $dir )= @_;
    my $path=  "" eq $parent  ?  $dir  :  "$parent/$dir";
    if(  ! chdir( $dir )  ) {
        warn "Can't chdir($dir) ", "" eq $parent ? "" : "from $path", 
+": $!\n";
        return;
    }
    opendir( DH, "." )  or  die "Can't read $path: $!\n";
    my $has= 0;
    my @dirs;
    my $file;
    while(  defined( $file= readdir(DH) )  ) {
        next   if  $file =~ /^\.\.?$/  &&  $file !~ /\s/;
        if(  -l $file  ||  ! -d _  ) {
            $has |= FILE;
        } else {
            $has |= DIR;
            push @dirs, $file
        }
    }
    closedir(DH);
    if(  $has  ) {
        $has &= ~DIR;
        for(  @dirs  ) {
            $has |= DIR
                if  ! dropEmpty( $path, $_ );
        }
    }
    chdir( ".." )  or  die "Can't return up from $path: $!\n";
    if(  0 == $has  ) {
        if(  ! rmdir($dir)  ) {
            $has= 1;
            warn "Can't delete empty $path: $!\n";
        } else {
            warn "Deleted empty directory $path.\n";
        }
    }
    return 0 == $has;
}

sub main {
    die "Usage: rmtd dir [...]\nRemoves eMpTy Directories\n"
        if  ! @_;
    for(  @_  ) {
        dropEmpty( "", $_ );
    }
}
Replies are listed 'Best First'.
•Re: Remove eMpTy Directories
by merlyn (Sage) on Nov 18, 2002 at 21:57 UTC
        Quite inefficient. perl -MFile::Find -e 'find( { wanted => sub {}, postprocess => sub { rmdir $File::Find::name } }, @ARGV )'

        Makeshifts last the longest.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: sourcecode [id://213798]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (3)
As of 2024-11-03 04:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    chatterbot is...






    Results (13 votes). Check out past polls.