通过用零填充批量重命名顺序文件 [英] Batch rename sequential files by padding with zeroes
问题描述
我有一堆这样命名的文件:
I have a bunch of files named like so:
output_1.png
output_2.png
...
output_10.png
...
output_120.png
重命名它们以匹配约定的最简单方法是什么,例如最多四位小数,以便文件命名:
What is the easiest way of renaming those to match a convention, e.g. with maximum four decimals, so that the files are named:
output_0001.png
output_0002.png
...
output_0010.png
output_0120.png
这在 Unix/Linux/BSD 中应该很容易,尽管我也可以访问 Windows.任何语言都可以,但我对一些非常简洁的单行代码感兴趣(如果有的话?).
This should be easy in Unix/Linux/BSD, although I also have access to Windows. Any language is fine, but I'm interested in some really neat one-liners (if there are any?).
推荐答案
Python
import os
path = '/path/to/files/'
for filename in os.listdir(path):
prefix, num = filename[:-4].split('_')
num = num.zfill(4)
new_filename = prefix + "_" + num + ".png"
os.rename(os.path.join(path, filename), os.path.join(path, new_filename))
假设所有以output_"开头并以.png"结尾的文件都是有效文件,您可以编译一个有效文件名列表:
you could compile a list of valid filenames assuming that all files that start with "output_" and end with ".png" are valid files:
l = [(x, "output" + x[7:-4].zfill(4) + ".png") for x in os.listdir(path) if x.startswith("output_") and x.endswith(".png")]
for oldname, newname in l:
os.rename(os.path.join(path,oldname), os.path.join(path,newname))
<小时>
重击
(来自:http://www.walkingrandomly.com/?p=2850)
换句话说,我将 file1.png 替换为 file001.png,将 file20.png 替换为 file020.png 等等.下面是如何在 bash 中做到这一点
In other words I replace file1.png with file001.png and file20.png with file020.png and so on. Here’s how to do that in bash
#!/bin/bash
num=`expr match "$1" '[^0-9]*([0-9]+).*'`
paddednum=`printf "%03d" $num`
echo ${1/$num/$paddednum}
将上述内容保存到名为zeropad.sh
的文件中,然后执行以下命令使其可执行
Save the above to a file called zeropad.sh
and then do the following command to make it executable
chmod +x ./zeropad.sh
然后您可以使用 zeropad.sh
脚本,如下所示
You can then use the zeropad.sh
script as follows
./zeropad.sh frame1.png
返回结果
frame001.png
剩下的就是使用这个脚本来重命名当前目录中的所有 .png 文件,以便它们被零填充.
All that remains is to use this script to rename all of the .png files in the current directory such that they are zeropadded.
for i in *.png;do mv $i `./zeropad.sh $i`; done
<小时>
Perl
(来自:零垫重命名例如 Image (2).jpg -> Image (002).jpg)
use strict;
use warnings;
use File::Find;
sub pad_left {
my $num = shift;
if ($num < 10) {
$num = "00$num";
}
elsif ($num < 100) {
$num = "0$num";
}
return $num;
}
sub new_name {
if (/.jpg$/) {
my $name = $File::Find::name;
my $new_name;
($new_name = $name) =~ s/^(.+/[w ]+()(d+))/$1 . &pad_left($2) .')'/e;
rename($name, $new_name);
print "$name --> $new_name
";
}
}
chomp(my $localdir = `pwd`);# invoke the script in the parent-directory of the
# image-containing sub-directories
find(&new_name, $localdir);
<小时>
重命名
同样来自上面的答案:
Rename
Also from above answer:
rename 's/d+/sprintf("%04d",$&)/e' *.png
这篇关于通过用零填充批量重命名顺序文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!