How to rename files in a for loop in Perl

I run a Perl script and try to rename the files as shown below.

I have a list of * .ru.jp files in a folder with other unrelated files. I would like to rename the number that I have as a counter.

In Bash, I would do so ...

for i in $(ls *.ru.jp); do x=${i%%.*}; mv $i  "$x"t"$counter".ru.jp ;done

For example, myfile.ru.jp will be renamed to myfilet1.ru.jp if the counter is 1. "t" is just a naming convention, indicating t1, t2 ... etc. And there is an external cycle that will ultimately mean mafilet2.ru.jp, etc. As the counter variable increases.

I would like to know how I could write and present similar ones for a loop like in a Perl script?

Thank.

-joey

+3
6
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
+8

Perl glob rename :

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++;
}
+7

, , :

#! /usr/bin/perl

my $count = 0;
for (<*.ru.jp>)
{
        $count++;
        /(.+)\.ru\.jp/;
        rename $_, $1 . "t" . $count . ".ru.jp";
}
+1
$count = 1;
for (<*.ru.jp>)
{
        ($filename)=(/^(.*?)\.ru.jp$/);
        rename $_,$filename."t".$count++.".ru.jp";
}
+1
use strict;
my $c=0;
rename("$1.ru.jp", "$1" . $c++ . ".ru.jp") while <*.ru.jp> =~ /(.+).ru.jp/;
+1
my $counter=0;
while(my $file=<*.ru.jp>){
    $counter++;
    my ($front,$back) = split /\./,$file,2;
    $newname="$front$counter".".t."."$back\n";
    rename $file $newname;
}
+1
source

Source: https://habr.com/ru/post/1726452/


All Articles