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条回答
等我变得足够好
2楼-- · 2020-03-03 09:10

In my debian it works well with rename, tested with 300 files.

 perl -e 'map `touch door$_.txt`, 1..300;'
 rename 's/(\d+)\.txt/sprintf("%03d.txt", $1)/e' *.txt
查看更多
We Are One
3楼-- · 2020-03-03 09:18

Is this a one-time thing? If so, I'm going to suggest something that might seem to be a cop out by many programmers here:

Pipe the output of your command (find -type d | sort -r | grep ' [1-9][0-9]$') to a file and use an editor along with some global search/replace magic to create a script that does the renames.

Then throw away the script.

There's little fuss and little chance that you'll end up shooting yourself in the foot by having some attempt at a clever (but inadequately debugged) one-liner go off into the weeds on your files.

查看更多
唯我独甜
4楼-- · 2020-03-03 09:21
perl -e 'foreach $f (glob("File\\ Name*")) { $nf = $f; $nf =~ s/(\d+)$/sprintf("%03d",$1)/e; print `mv \"$f\" \"$nf\"`;}'

A bit overkill maybe, but it does what is asked.

查看更多
孤傲高冷的网名
5楼-- · 2020-03-03 09:27

if your remote has 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 do actual renaming

查看更多
虎瘦雄心在
6楼-- · 2020-03-03 09:29

you could do something using perl or ruby.

put all this files in the same directory

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
查看更多
够拽才男人
7楼-- · 2020-03-03 09:30

Run two commands, in this order:

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

First one renames everything less than 10 and prepends a zero. The second one renames everything less than 100 and prepends a zero. The result should be three digits for all filenames.

查看更多
登录 后发表回答