问题描述
我有一些文件:
$ ls
00000.ABC
00001.ABC
00002.ABC
00003.ABC
00004.ABC
00005.ABC
我想将它们更改为以某个数字开头,例如00055.ABC
,以便新文件看起来像:
I want to change these to start at a certain number, for example 00055.ABC
so the new files look like:
$ ls
00055.ABC
00056.ABC
00057.ABC
00058.ABC
00059.ABC
00060.ABC
我了解for循环遍历每个文件,例如for file in ls { }
,但是我不确定以某个数字开头的递增数字,因此不胜感激.
I understand about for loops to loop through each file, for example for file in ls { }
but I'm not sure about the incrementing number starting at a certain number so appreciate any help.
推荐答案
这应该有效:
for f in *.ABC; do
num=$(basename "$f" .ABC)
num2=$(printf "%05d" $((num + 55)))
echo mv "$f" "$num2.ABC"
done
注意:
-
我假设您的文件都遵循数字模式,后跟
.ABC
,以便basename $f .ABC
提取数字.如果此假设不成立,则必须调整num=
行.
I am assuming your files all follow the pattern of digits followed by
.ABC
, so thatbasename $f .ABC
extracts the number. You'll have to adjust thenum=
line if this assumption does not hold.
$(( ... ))
是用于执行算术运算的bash
语法.
$(( ... ))
is the bash
syntax to do arithmetic operations.
(printf "%05d" ...)
在此处在数字前面填充零,否则您将得到55
等.
(printf "%05d" ...)
is here to pad zeroes in front of the number, otherwise you'd just get 55
etc.
在确信执行正确的操作后,请删除echo
.
Remove the echo
once you're convinced it's doing the right thing.
编辑警告:新的文件名集不应与旧的文件名集重叠,否则您可能会丢失一些文件.仔细选择mv
命令的运行顺序可以解决此问题,但是在文件重命名时将其放置在新目录中,然后再将其移回将更简单.
EDIT Warning: the new set of filenames should not overlap the old set of filenames, or you might lose some files. Carefully choosing the order the mv
commands are run could solve the issue, but putting the files in a new directory as they are renamed and moving them back after would be much simpler.
编辑:
@MarkSetchell在注释中指出,您想要不基于原始文件名的顺序编号,在这种情况下,此循环将起作用:
@MarkSetchell pointed out in the comments that you want sequential numbering that is not based on the original file names, in which case this loop would work instead:
i=55 # choose your starting destination file number here
for f in *.ABC; do
dest=$(printf "%05d" $i).ABC
echo mv "$f" "$dest"
i=$((i + 1))
done
这篇关于重命名文件,其编号从特定编号开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!