9

I have a bunch of .jpg files with random names. I want a bash script to rename them like this:

basename-0.jpg
basename-1.jpg
basename-2.jpg
.
.
.
.
basename-1000.jpg

I wrote this:

n = 0;
for file in *.jpg ; do mv  "${file}" basename"${n}".jpg; n+=1;  done

But the problem with the above bash is that in the loop, n is considered as string so n+1 just adds another '1' to the end of newly moved file. Appreciate your hints.

qliq
  • 11,695
  • 15
  • 54
  • 66

3 Answers3

14

Use $((expression)) for arithmetic expansion in bash shell

n=0;
for file in *.jpg ; do mv  "${file}" basename"${n}".jpg; n=$((n+1));  done
Yann Moisan
  • 8,161
  • 8
  • 47
  • 91
  • How would you do adapt this answer for the case where you don't know the file extension ahead of time? Like say I have a directory of mixed extensions (that I don't know ahead of time) and I want to blindly name them all with an incrementing pattern, but keep their existing extension type. – Raleigh L. Sep 13 '22 at 05:52
4

Bash can also pre/post increment/decrement variable values using arithmetic evaluation syntax like ((var++)).

n=0;
for file in *.jpg ; do mv  "${file}" basename"${n}".jpg; ((n++));  done
John B
  • 3,566
  • 1
  • 16
  • 20
3

Did you want 'basename' or $(basename)? More generalized forms are:

# create basename-0.jpg, basename-1.jpg, ... basename-n.jpg
e='jpg'; j=0; for f in *.$e; do mv "$f" basename-$((j++)).$e; done

or

# preserve stem: <stemA>-0.jpg, <stemB>-1.jpg, ... <stem?>-n.jpg
e='jpg'; j=0; for f in *.$e; do mv "$f" "${f%.*}"-$((j++)).$e; done
AsymLabs
  • 933
  • 9
  • 15