Bash Shell Script – Batch Rename Files to Sequential Numbers

bashrenameshellshell-script

I am trying to batch-rename a bunch of files in my shell, and even though there is plenty of material about it on the internet, I cannot seem to find a solution for my specific case.

I have a bunch of files that have (what appears to be) a "timestamp-id":

abc_128390.png
abc_138493.png
abc_159084.png
...

that I'd like to exchange for a counter:

abc_001.png
abc_002.png
abc_003.png
...

My (plenty) naïve approach would be something like:

mv abc_*.png abc_{001..123}.png

Also, I could not figure out a way to make it work with a for-loop.

FWIW, unfortunately rename is not available on this particular system.

Any advice would be greatly appreciated!

Best Answer

I can't think of a solution that handles incrementing the counter in a more clever way, but this should work:

i=0
for fi in abc_??????.png; do
    mv "$fi" abc_$i.png
    i=$((i+1))
done

It should be safe to use abc_*.png because it is expanded before the first mv is ever executed, but it can be useful to be very specific in that you only want files with a six-character timestamp at the end.

Related Question