tian
asked on
more elegant one?
hello,
a perl code should find in specified directory recursively all the file ended with given suffix1 and rename it to file ended with given suffix2.(behave like mv *.aa *.bb)
$suffix1='.aa';
$suffix2='.bb';
@f=`find $path -type f -name '*$suffix1'`;
foreach $x (@f){
chop($x);#get rid of \n
$tem=$x;
$tem=~ s/$suffix1$/$suffix2/;
`mv $x $tem`;
}
I wonder whether there is better way to implement it.
a perl code should find in specified directory recursively all the file ended with given suffix1 and rename it to file ended with given suffix2.(behave like mv *.aa *.bb)
$suffix1='.aa';
$suffix2='.bb';
@f=`find $path -type f -name '*$suffix1'`;
foreach $x (@f){
chop($x);#get rid of \n
$tem=$x;
$tem=~ s/$suffix1$/$suffix2/;
`mv $x $tem`;
}
I wonder whether there is better way to implement it.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks ahoffmann. Before I close this question, can someone provide me an implementation based on bertvermeerbergen's idea?
use File::Find;
find(\&DoSomething, $path);
sub DoSomething {
my $tem;
-f && ($tem=$_)=~s/\Q$suffix1\E$ /$suffix2/ && rename($_,$tem);
}
find(\&DoSomething, $path);
sub DoSomething {
my $tem;
-f && ($tem=$_)=~s/\Q$suffix1\E$
}
ASKER
thank you
tian, are you shure that the points are for my and not for ozo's suggestion?
Example:
#-- The subroutine called by find for every entry
sub DoSomething
{
#-- $File::Find::dir contains the current directory (chdir() has been done)
#-- $_ contains the current file or subdir name
#-- $File::Find::name is "$File::Find::dir/$_"
here, you check for matching entry and then use perl rename function
}
#-- (this is in your main or some other subroutine)
#-- Parameters:
#-- 1: A reference to the subroutine to be called for every item
#-- 2: The top-level directory you want to scan
find(\&DoSomething, $path);