Reputation: 51
I am running a Perl script and trying to accomplish renaming files as below.
I have a list of *.ru.jp
files in a folder with other non-related files. I would like to rename with a number which I have got as a counter variable.
In Bash, I would do it as:
for i in $(ls *.ru.jp); do x=${i%%.*}; mv $i "$x"t"$counter".ru.jp ;done
E.g., myfile.ru.jp
would be renamed as myfilet1.ru.jp
if the counter is 1. "t" is just a naming to indicate t1,t2...etc. And there is an outer loop above all which eventually will label mafilet2.ru.jp
and so on as the counter variable increases.
I would like to know how could I write and represent a similar for loop as in a Perl script?
Upvotes: 5
Views: 1651
Reputation: 342263
my $counter=0;
while(my $file=<*.ru.jp>){
$counter++;
my ($front,$back) = split /\./,$file,2;
$newname="$front$counter".".t."."$back\n";
rename $file $newname;
}
Upvotes: 1
Reputation:
use strict;
my $c=0;
rename("$1.ru.jp", "$1" . $c++ . ".ru.jp") while <*.ru.jp> =~ /(.+).ru.jp/;
Upvotes: 1
Reputation: 139421
perl -e 'for $old (@ARGV) {
++$counter;
if (($new=$old) =~ s/(\.ru\.jp)\z/t$counter$1/) {
rename $old => $new or warn "$0: rename: $!\n";
}
}' *.ru.jp
Upvotes: 8
Reputation: 62019
You could use Perl's file glob and built-in rename function as follows:
use warnings;
use strict;
my $i = 1;
for (<*.ru.jp>) {
my $file = $_;
s/\.ru\.jp$//;
my $new = $_ . 't'. $i . '.ru.jp';
rename $file, $new or die "Can not rename $file as $new: $!";
$i++;
}
Upvotes: 7
Reputation: 454920
$count = 1;
for (<*.ru.jp>)
{
($filename)=(/^(.*?)\.ru.jp$/);
rename $_,$filename."t".$count++.".ru.jp";
}
Upvotes: 1
Reputation: 826
I tried this and it seems to do the job:
#! /usr/bin/perl
my $count = 0;
for (<*.ru.jp>)
{
$count++;
/(.+)\.ru\.jp/;
rename $_, $1 . "t" . $count . ".ru.jp";
}
Upvotes: 1