
Laurent_R
Veteran
/ Moderator
Aug 10, 2014, 8:03 AM
Post #5 of 6
(13708 views)
|
Re: [javedakbar] Perl script that recursively deletes all subdirectories but leaving one
[In reply to]
|
Can't Post
|
|
Then you probably want to use the standard File::Find (http://search.cpan.org/~rjbs/perl-5.20.0/ext/File-Find/lib/File/Find.pm) module to walk through the directory. If you want to code it yourself, you could do a recursive function traversing the directory tree. Something like like this:
use strict; use warnings; die "Need to pass the directory to be deleted as argument\n" unless @ARGV; my $start_dir = $ARGV[0]; traverse_dir ($start_dir); sub traverse_dir { my $path = shift; my @dir_entries = glob("$path/*"); foreach my $entry (@dir_entries) { next if $entry eq "dir3" or $entry eq "." or $entry eq ".."; print "File to be deleted = $entry\n" if -f $entry; traverse_dir($entry) if -d $entry; print "Directory to be deleted = $entry\n" if -d $entry; } } The above program just prints out the files and directories to be deleted, without actually deleting them, for the purpose of carefully testing what the actual program would do. Once you are happy that it is picking up what you want to delete (and only that), then you can change the two print code lines as follows: Replace:
print "File to be deleted = $entry\n" if -f $entry; with:
print "deleting file $entry\n" if -f $entry; unlink $entry if -f $entry; and:
print "Directory to be deleted = $entry\n" if -d $entry; with:
print "deleting directory $entry \n" if -d $entry; rmdir $entry if -d $entry; Whenever the program finds a directory, it first goes into that directory (by calling recursively traverse_dir) and deletes everything under it, so that the directory is empty (and can be deleted) when it tries to delete the directory. You don't need to cd to the directory for it to work, just pass a relative or absolute path as an argument to the program. Please be VERY careful using the modified program, you might eradicate an entire file system if you pass the wrong parameter. Also note that I have tested the file and directory printing version at the top of this post, I haven't tried a version actually deleting the entries.
|