更改一系列文件的数字索引

时间:2015-12-09 07:33:07

标签: loops rename

我的Linux帐户中有456个文件位于共享计算机上,名称如下:

ABC_0,ABC_1,...,ABC_455

我想在其索引中添加911并将其重命名为

ABC_911,ABC_912,...,ABC_1356

之前我曾经这样做过,但我找不到我用过的脚本。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

这可能不是最好的方式,但它会起作用:

import os, sys

def main():
    oldname_prefix = raw_input('Input old name prefix: ')
    starting_index = raw_input('Input starting index: ')
    ending_index = raw_input('Input the ending index (the size of the largest current file): ')
    file_format = raw_input('Input file format: ')
    new_starting_index = raw_input('Input the starting index of the new file names: ')
    i = int(starting_index)
    end = int(ending_index)
    difference = int(new_starting_index) - i
    while i <= end:
        old_name = oldname_prefix + str(i) + file_format
        new_name = oldname_prefix + str(i + difference) + file_format
        os.rename(old_name, new_name)
        i += 1

if __name__ == '__main__':
    main()

创建它,将其另存为“renaming.py”或其他内容,并将其放在与要重命名的文件相同的目录中。然后在命令行python renaming.py键入。当它提示你时,输入“ABC_”,然后输入“0”,然后输入“455”,然后输入它们的任何文件格式(如果没有,只要按下输入而不输入任何内容),然后“900”例如,如果它们是.txt文件,它看起来像这样:

Input old name prefix: ABC_
Input starting index: 0
Input the ending index (the size of the largest current file): 455
Input file format: .txt
Input the starting index of the new file names: 900

为了加倍安全,我建议先将一小部分文件复制到另一个位置然后尝试使用,以防有些问题无法正常工作,但它对我来说很合适。

这是另一种可能性,仅使用Bash。

user@computer:~/directory$ a=0
user@computer:~/directory$ b=900
user@computer:~/directory$ for i in ABC_*; do old=$(printf "ABC_%1d" "$a"); new=$(printf "ABC_%1d" "$b"); mv -- "$old" "$new"; let a=a+1; let b=b+1; done

首先确保现在将a设置为文件的起始值,b是最后文件的起始值。然后,此函数循环遍历当前目录中格式为“ABC_ *”的每个文件,获取其当前名称,获取其所需名称,然后重命名它。如果文件具有文件扩展名,则在printf "ABC_%1d"位的两者中,将其更改为“printf”ABC_%1d.jpg“,或者扩展名为。

相关问题