Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Perl, how can I find and remove files with a specific suffix?

Tags:

perl

I need to write a function in Perl that removes all files with the .rc suffix under a certain location and its subdirectories (lets call it targetroot).

I am working in NT env, so I can't use system commands like find, or rm. I have tired to do it with unlink and find options but didn't manage.

What I have tried is:

print "\n<<<    Removing .rc files from $targetRoot\\20140929_231622    >>>\n";
my $dir = "$targetRoot\\20140929_231622";
find(\&wanted, $dir);
sub wanted 
{ 
  unlink glob "*.rc";
}

Can someone show me how to do it?

like image 727
user3720181 Avatar asked Oct 18 '25 17:10

user3720181


2 Answers

You're pretty close. File::Find is the tool for the job here. Try putting your wanted() as:

sub  wanted {
    # $_ set to filename; $File::Find::name set to full path.
    if ( -f and m/\.rc\z/i ) {
        print "Removing $File::Find::name\n"; 
        unlink ( $File::Find::name );
    }
}

Try it first without the unlink of course, to verify you get the right targets. Bear in mind File::Find will recurse down the directory structure by default.

like image 111
Sobrique Avatar answered Oct 20 '25 16:10

Sobrique


You need to modify the wanted subroutine:

sub wanted { /\.rc$/ && ( unlink $File::Find::name or die "Unable to delete $_: $!" ) }

From the File::Find documentation

The wanted function

The wanted() function does whatever verifications you want on each file and directory. Note that despite its name, the wanted() function is a generic callback function, and does not tell File::Find if a file is "wanted" or not. In fact, its return value is ignored.

The wanted function takes no arguments but rather does its work through a collection of variables.

`$File::Find::dir` is the current directory name,

`$_` is the current filename within that directory

`$File::Find::name` is the complete pathname to the file.
like image 28
Zaid Avatar answered Oct 20 '25 14:10

Zaid