How can I easily bulk rename files with Perl?

2020-03-03 08:59发布

I have a lot of files I'm trying to rename, I tried to make a regular expression to match them, but even that I got stuck on the files are named like:

File Name 01

File Name 100

File Name 02

File Name 03

etc, I would like to add a "0" (zero), behind any of file that are less than 100, like this:

File Name 001

File Name 100

File Name 002

File Name 003

The closest I got to so much as matching them was using this 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 is of any help, all this is being done via SSH.

9条回答
你好瞎i
2楼-- · 2020-03-03 09:30
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);
    }
}
查看更多
淡お忘
3楼-- · 2020-03-03 09:34
find . -type d -print0 | xargs -0 rename 's/(\d+)/sprintf "%03d", $1/e' 

or something like that, provided

  1. You have GNU find and GNU xargs (for -print0 and -0)
  2. You have the 'rename' utility that comes with perl
  3. There's only one group of digits in the filename. If there's more than one, then you need to do something with the regex to make it only match the number you want to reformat.
查看更多
姐就是有狂的资本
4楼-- · 2020-03-03 09:36

I think mmv is your friend here.

查看更多
登录 后发表回答