Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Loops 更改一系列文件的编号索引_Loops_Rename - Fatal编程技术网

Loops 更改一系列文件的编号索引

Loops 更改一系列文件的编号索引,loops,rename,Loops,Rename,我的linux帐户中有456个文件,在一台名为以下内容的共享计算机上: 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 ABC_0,ABC_1,…,ABC_

我的linux帐户中有456个文件,在一台名为以下内容的共享计算机上:

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
ABC_0,ABC_1,…,ABC_455

我想将911添加到它们的索引中,并将它们重命名为

ABC_911,ABC_912,…,ABC_1356

我以前做过一次,但是我找不到我用于它的脚本


非常感谢您的帮助。

这可能不是最好的解决方法,但在紧要关头它会起作用:

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()
为了更加安全,我建议您先将文件的一小部分复制到另一个位置,然后在这些位置上进行尝试,以防出现一些不正常的情况,但对我来说效果很好


这里有另一种可能性,只使用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”,或任何扩展名。

哪个平台?哪种语言?谢谢你的帮助。但是有没有什么方法可以基于linux命令本身而不是编写代码呢!谢谢。我喜欢基于Bash的第二个