简体   繁体   English

如何在文件名中以前导零递增数字

[英]How to increment number with leading zeros in filename

I have a set of files, not necessarily of the same extension. 我有一组文件,不一定具有相同的扩展名。 These files were created by a Python script that iterates over some files (say x.jpg, y.jpg, and z.jpg), and then numbers them with zero-padding so that the numbers are of length 7 characters (in this example, the filenames become 0000001 - x.jpg , 0000002 - y.jpg , and 0000003 - z.jpg ). 这些文件是由Python脚本创建的,该脚本对某些文件(例如x.jpg,y.jpg和z.jpg)进行迭代,然后使用零填充对其进行编号,以使这些数字的长度为7个字符(在此示例中) ,文件0000001 - x.jpg 0000002 - y.jpg 0000001 - x.jpg0000002 - y.jpg0000003 - z.jpg )。

I now need a script (any language is fine, but Bash/zsh is preferred), that will increment these numbers by an argument. 我现在需要一个脚本(任何语言都可以,但是Bash / zsh是首选),它将通过一个参数增加这些数字。 Thereby renaming all the files in the directory. 从而重命名目录中的所有文件。 For example, I'd like to call the program as (assuming a Shell script): 例如,我想调用该程序为(假设使用Shell脚本):

./rename.sh 5

The numbers in the final filenames should be padded to length 7, and it's guaranteed that there's no file initially whose number is 9999999. So the resulting files should be 0000006 - x.jpg , 0000007.jpg , 0000008.jpg . 最终文件名中的数字应填充为长度7,并确保最初没有文件号为9999999。因此,生成的文件应为0000006 - x.jpg0000007.jpg0000008.jpg It's guaranteed that all the files initially are incremental; 确保最初所有文件都是增量文件; that is, there are no gaps in the numbers. 也就是说,数字之间没有差距。

I can't seem to do this easily at all in Bash, and it seems kind of like a chore even in Python. 在Bash中,我似乎根本不容易做到这一点,即使在Python中,这似乎也很繁琐。 What's the best way to do this? 最好的方法是什么?

Edit: Okay so here are my efforts so far. 编辑:好的,到目前为止,这是我的努力。 I think the leading 0s are a problem, so I removed them using rename: 我认为前导0是个问题,因此我使用重命名将其删除:

rename 's/^0*//' *

Now with just the numbers left, I'd ideally use a loop, something like this, but I'm not exactly familiar with the syntax and why this is wrong: 现在只剩下数字了,理想情况下,我将使用一个类似这样的循环,但是我对语法及其错误原因并不十分熟悉:

for file in "(*) - (*)" ; do mv "${file}" "$(($1+5)) - ${2}" ; done

The 5 there is just hard-coded, but I guess changing that to the first argument shouldn't be too big a deal. 那里的5只是硬编码的,但是我想将其更改为第一个参数应该没什么大不了的。 I can then use another loop to add the 0s back. 然后,我可以使用另一个循环将0加回来。

import sys, glob, re, os
# Get the offset at the first command-line argument
offset = int(sys.argv[1]) 

# Go through the list of files in the reverse order
for name in reversed(glob.glob('*.jpg')):
    # Extract the number and the rest of the name
    i, rest = re.findall("^(\d+)(.+)", name)[0]
    # Construct the new file name
    new_name = "{:07d}{}".format(int(i) + offset, rest)
    # Rename
    os.rename(name, new_name)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM