Using Perl to Rename File

Hi,

Can someone help me with a perl file to rename some files please? I can do it with regular command line using the below code, but I need to include this in another script and the other script is perl. I know nothing of perl.

for file in C*
do
     newfilename=`echo $file | cut -c8-21-`
     mv $file $newfilename
done
perl -e 'foreach (@ARGV) { rename($_, substr($_,7,14)) }' C*

Here's what I'm trying to do:

rename files like this:
ABCDEFG20090904024156.00565.txt
to this:
ABCDEFG.00565.txt

Like I said, I know nothing of perl. Will you code do this? Oh and the first 7 characters (ABCDEFG) are never the same.

foreach (<*.txt>)
{
rename($_, substr($_,0,7) . substr($_,21));
}

If you're doing this in an existing script I'm assuming you'll need to glob the files (angle braces in the code) rather than using @ARGV.

The second substr can also be expressed as a negative offset (substr($_,-10)), which would allow a variable center part - if say you happen to run into a 'ABCDEFG20090904024156a.00565.txt'.

Hi, thanks for the above code. It did work. However, now I need to add a series of letters to renamed files.

So I need to change the file from: ABCDEFG20090904024156.00565.txt
To: ABCDEFGZZZZZ00565.txt

Can I just add these letters to a spot on your code to get it to work? take out the "." and add ZZZZZ in it's place.

---------- Post updated at 10:18 AM ---------- Previous update was at 09:25 AM ----------

I think I got it:

foreach (<*.txt>)
{
rename($_, substr($_,0,7) . ($_,ZZZZZ) . substr($_,22));
}

---------- Post updated at 11:20 AM ---------- Previous update was at 10:18 AM ----------

Just one more thing :slight_smile:

Need to drop the .txt extension.

:smiley:

drop the .txt simply with one more substr.,

foreach (<*.txt>)
{
rename($_, substr($_,0,7) . ($_,ZZZZZ) . substr($_,22,5));
}

Cool. That worked. I need to learn some of this perl stuff. Coming in handy these days. Those "Teach Yourself Perl in 24hrs" books any good?

I recommend the O'Reilly book "Learning Perl"

Beginning Perl is a pretty good resource, and the price is right.

Also, the ($_,ZZZZZ) bit is unnecessary - use the following:

rename($_, substr($_,0,7) . "ZZZZZ" . substr($_,22));