[英]Bash script to add constant to file names
I need a bash script to rename the files in a directory.我需要一个 bash 脚本来重命名目录中的文件。 The names have the format
<name>_<number>
(eg bob_12
, alice_233
).名称的格式为
<name>_<number>
(例如bob_12
、 alice_233
)。 The script must change them to <name>_<number+k>
(eg, if k=20, bob_32
, alice_253
).脚本必须将它们更改为
<name>_<number+k>
(例如,如果 k=20, bob_32
, alice_253
)。 Can someone help?有人可以帮忙吗?
$ ls
alice_253 bob_32
$ k=20
$ for old in *; do new=${old%_*}_$((${old#*_}+k)); mv "$old" "$new"; done
$ ls
alice_273 bob_52
This is just an example though.这只是一个例子。 It won't work properly if there are files whose names have:
如果存在名称具有以下内容的文件,它将无法正常工作:
If we wanted to cover those cases as well, assuming filenames may not overlap (eg foo_100
and foo_120
when k=20
, in which case we'd need to sort them in reverse order first), we'd do:如果我们也想涵盖这些情况,假设文件名可能不重叠(例如
foo_100
和foo_120
时k=20
,在这种情况下我们需要先以相反的顺序对它们进行排序),我们会这样做:
# handle -foo_123
# skip foo, foo_bar, foo_012,
# and foo_bar_123
k=20
for old in ./*_*; do
case $old in
(*_*_*) ;&
(*_*[!0-9]*) ;&
(*_0*) continue
esac
new=${old%_*}_$((${old#*_}+k))
mv "$old" "$new"
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.