简体   繁体   中英

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 ).

I now need a script (any language is fine, but Bash/zsh is preferred), that will increment these numbers by an argument. Thereby renaming all the files in the directory. For example, I'd like to call the program as (assuming a Shell script):

./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 . 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. 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:

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. I can then use another loop to add the 0s back.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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