Shell script to rename files

I have a bunch of files that I need renamed.  The files are names like 20509220.jpg  20509220_1.jpg 20509220_2.jpg etc...  where the 20509220 part is just some number.
I want to change the names of the files so there are no files without a _[1-9] at the end.  So I need to:

20509220.jpg --> 20509220_1.jpg
20509220_1.jpg --> 20509220_2.jpg
20509220_2.jpg --> 20509220_3.jpg
.....
20509220_9.jpg --> 20509220_10.jpg

just to make sure I'm being clear, I have files with the following filenames (the number before the underscore could be any number):

20509220.jpg
20509220_1.jpg
20509220_2.jpg
20509220_3.jpg
20509220_4.jpg
20509220_5.jpg
20509220_6.jpg
20509220_7.jpg
20509220_8.jpg
20509220_9.jpg

and I want to change them all to have filenames like:

20509220_1.jpg
20509220_2.jpg
20509220_3.jpg
20509220_4.jpg
20509220_5.jpg
20509220_6.jpg
20509220_7.jpg
20509220_8.jpg
20509220_9.jpg
20509220_10.jpg

If anyone needs more clarification, let me know!!  I'm fairly good with Linux, but not nearly good enough to create a script like this.  Any help is appreciated.  Thanks!!
btw...I'm using bash.
wotechAsked:
Who is Participating?
 
ozoCommented:
#!/bin/bash
perl -e 'rename $_->[0],"$_->[1]_".($_->[3]+1).".jpg" or warn "$_->[0] $!" for sort{0+$b->[3]<=>0+$a->[3]}map{[/((.*?)(_(\d+))?\.jpg$)/]}@ARGV' *.jpg
0
 
ahoffmannCommented:
perl -e 'for $x (sort{$a<=>$b}<*.jpg>){$n=$x;$n=~s/([^_]*)(_\d+)?\.jpg/$1/;rename$x,$n."_".++$y.".jpg"}'
0
 
ozoCommented:
I think you need to do higher $y before smaller $y, otherwise you
rename "20509220_1.jpg", "20509220_2.jpg" over the old 20509220_2.jpg
0
 
ahoffmannCommented:
ozo, I guessed that too when I wrote that, but in my tests it didn't overwrite, suprise ;-)
don't know why perl is that clever here, but it worked for me with given test example from question, still wondering ...
Anyway, reversing the order is more secure.
0
 
wotechAuthor Commented:
thanks ozo, worked great.
just for others that are reading this in the future....
everytime you run the script in the folder with the images, the suffix numbers (_1, _2, etc) will be increased by one.   so if you have 20509220_1.jpg, 20509220_2.jpg, etc  and you run the script, you get  20509220_2.jpg, 20509220_3.jpg, etc.

It doesn't really matter, it just threw me for a loop so I thought I'd mention it.  
Thx again!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.