I need a bash script to rename the files in a directory. The names have the format <name>_<number>
(eg bob_12
, alice_233
). The script must change them to <name>_<number+k>
(eg, if 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:
# 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
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.