Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash batch rename files in order

I have a bunch of files in the same directory with names like:

IMG_20160824_132614.jpg

IMG_20160824_132658.jpg

IMG_20160824_132738.jpg

The middle section is the date and last section is time the photo was taken. So if I were to sort these files by their name the result would be the same as sorting by date/time modified

I'd like to batch rename these files using bash to something of the form:

1-x-3.jpg

Where the x represents the place of the file in the sequential ordering (ordered by name/time modified)

So the 3 examples above would be renamed to:

1-1-3.jpg

1-2-3.jpg

1-3-3.jpg

Is there a bash command that can achieve this? Or is a script required?

like image 253
Simon Avatar asked Aug 24 '16 21:08

Simon


1 Answers

Try:

i=1; for f in *.jpg; do mv "$f" "1-$((i++))-3.jpg"; done

For example, using your file names:

$ ls
IMG_20160824_132614.jpg  IMG_20160824_132658.jpg  IMG_20160824_132738.jpg
$ i=1; for f in *.jpg; do mv "$f" "1-$((i++))-3.jpg"; done
$ ls
1-1-3.jpg  1-2-3.jpg  1-3-3.jpg

Notes:

  1. When expanding *.jpg, the shell lists the files in alphanumeric order. This seems to be what you want. Note, though, that alphanumeric order can depend on locale.

  2. The sequential numbering is done with $((i++)). Here, $((...)) represents arithmetic expansion. ++ simply means increment the variable by 1.

like image 70
John1024 Avatar answered Sep 19 '22 13:09

John1024