1829820 Members
1964 Online
109993 Solutions
New Discussion

renaming files

 
SOLVED
Go to solution
kpatel786
Frequent Advisor

renaming files

Hi,

I have a list of files as below:

tacr013444.bdt
tacr013444.bid
tacr014444.bdt
tacr014444.bid
tacr015444.bdt
tacr015444.bid
tacr016444.bdt
tacr016444.bid

I am trying to rename the 444 character to 344 as below

tacr013444.bdt ---> tacro13344.bdt
tacr013444.bid ---> tacro12344.bid
tacr014444.bdt ---> tacr014344.bdt
tacr014444.bid
tacr015444.bdt
tacr015444.bid
tacr016444.bdt
tacr016444.bid

Kindly assist with you inputs. Thanking you in advance
3 REPLIES 3
James R. Ferguson
Acclaimed Contributor
Solution

Re: renaming files

Hi:

You could do:

# cat ./myrename
#!/usr/bin/perl
use strict;
use warnings;
my $newname;
while (<>) {
chomp;
next unless -f $_;
if (m/^tacr\d+?444\..+/) {
( $newname = $_ ) =~ (s/(^tacr\d+?)444(\..+)/${1}344${2}/);
if ( -f $newname ) {
print +( "$newname already exists!\n" );
next;
}
rename( $_, $newname );
}
}

...run as:

# ./myrename file

...where 'file' contains your list of filenames.

This will not clobber existing files of the target name, but leave the old name intact.

Regards!

...JRF...
OldSchool
Honored Contributor

Re: renaming files

something along the lines of:

for a in `ls tacr*4444.*`
do
newname=`echo $a | sed 's/4444\./3444\./g'
echo $a $newname
# mv $a $newname
done

ought to get you started. beware of spaces in names, name collisions and such...as the above checks nothing and procedes blindly.

if it looks right when run, then uncomment the "mv" and run with it...
Hein van den Heuvel
Honored Contributor

Re: renaming files

I use PERL for such excercises.

First I make a test to 'see' that it will do the right thing.

For example using 'ls' to find the target files:

ls tac*444.b* | perl -lne 'chomp; $o = $_; s/444\.b/344.b/; print "rename $o, $_" '

Or using the perl glob:

perl -le 'while () { $o = $_; s/444\.b/344.b/; print "rename $o, $_" }'

When satisfied, remove the print and make it real:

perl -le 'while () { $o = $_; s/444\.b/344.b/; rename $o, $_ }'

Babys teps:

-e '...' # command follows in quotes.

while () # loop over glob results, putting each output in automatic variable $_.
{ # block
$o = $_; # make copy of original file name
s/444\.b/344.b/; # substitute $_ data, with anchors as needed
rename $o, $_ # Real work, as function call
} # end-of-block for while.


hth,
Hein.