How can I easily rename files using Perl?

I have a lot of files that I'm trying to rename, I tried to make a regular expression to match them, but even that I'm stuck in the files, they are called:

File name 01

File Name 100

File name 02

File name 03

etc., I would like to add “0” (zero) after any file that is less than 100, for example:

File name 001

File Name 100

File name 002

File name 003

The closest I came across matched them using this method find -type d | sort -r | grep '[1-9] [0-9] $', however I could not figure out how to replace them. Thanks in advance for any help you can offer me. Im on CentOS, if that helps, all this is done via SSH.

+5
9
perl -e 'foreach $f (glob("File\\ Name*")) { $nf = $f; $nf =~ s/(\d+)$/sprintf("%03d",$1)/e; print `mv \"$f\" \"$nf\"`;}'

, , , .

+12
find . -type d -print0 | xargs -0 rename 's/(\d+)/sprintf "%03d", $1/e' 

- ,

  • GNU find GNU xargs ( -print0 -0)
  • "rename", perl
  • . , - , , .
+9

? , -, :

(find -type d | sort -r | grep ' [1-9][0-9]$') / script, .

script.

, , ( ) .

+4

:

$ rename 's/File Name (\d)$/File Name 0$1/' *
$ rename 's/File Name (\d\d)$/File Name 0$1/' *

10 . 100 . .

+2

debian , 300 .

 perl -e 'map `touch door$_.txt`, 1..300;'
 rename 's/(\d+)\.txt/sprintf("%03d.txt", $1)/e' *.txt
+1

, mmv - .

0

- perl ruby.

dirlisting = DIR.entries('.')

dirListing.each do |file| 
 num = file.match(/\d+$/).to_i
 if num < 100
   find the position where start the number, with index and inject the 0 there.
 end
end
0
use strict;
use File::Copy;

my @files = glob 'File*Name*';

foreach my $filename (@files) {
    if ($filename =~ m`^.*File.*Name.*?(\d+)`) {
        my $number = $1;
        next if ($number > 99);
        rename $filename, sprintf("FileName%03d",$number);
    }
}
0

bash shell

for i in File*; 
do 
    case "${i##* }" in  [0-9][0-9] ) 
      echo  mv "$i" "${i% *} $(printf "%03d" ${i##* })" ;; 
    esac; 
done

remove echo to actually rename

0
source

All Articles