Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I'm trying to rename a directory full of images like so:

test.jpg
funny.gif
sad.png
filename.PNG
filenaaskjas.JPG

to:

1.jpg
2.gif
3.png
4.png
5.jpg

I've got it working except for the uppercase --> lowercase conversion:

i=1;
shopt -s nullglob;
for f in *.jpg *.gif *.png *.jpeg *.JPG *.JPEG *.GIF; do
    mv -- "$f" "$i.${f##*.}";
    ((i++));
done

I also want jpeg to become jpg.

share|improve this question

4 Answers 4

Try something like

ext=$( echo "$i.${f##*.}" | tr [A-Z] [a-z] )
mv -- "$f" $i$ext

or for fixed length file names.

dest=$(printf '08d%' $9)$( echo "$i.${f##*.}" | tr [A-Z] [a-z] )
mv -- "$f" $dest

c

share|improve this answer

You can use ${parameter/pattern/string} to search/replace and ${parameter,,pattern} to convert to lowercase.

i=1;
shopt -s nullglob;
for f in *.jpg *.gif *.png *.jpeg *.JPG *.JPEG *.GIF; do
    EXT="${f##*.}"
    EXT=${EXT,,}
    EXT=${EXT/jpeg/jpg}
    mv -- "$f" "$i.${EXT}";
    ((i++));
done
share|improve this answer
    
Requires, I believe, bash v4 for ${parameter,,pattern} –  glenn jackman Feb 15 '11 at 16:04
    
@glenn: Correct. If on bash 3, there's always EXT=$(echo $EXT|tr '[A-Z]' '[a-z]') –  chris Feb 15 '11 at 16:07

Two steps:

convert extensions:

for file in *.GIF; do mv $file ${file%GIF}gif; done
for file in *.jpeg; do mv $file ${file%jpeg}jpg; done
...

number files:

for file in *.gif *.jpg ...; do mv $file $i$file; ((i++)); done
share|improve this answer

If you have (p)rename, you can write this:

shopt -s nullglob;

i=1; 
for f in *.{jpg,JPG,jpeg,JPEG,png,PNG,gif,GIF}; do 
    rename 's/.*\.(.*)$/'$((i++))'.\L$1/; s/jpeg$/jpg/' "$f"; 
done
share|improve this answer
1  
Simpler: rename 'next unless -e; ++$i; s/.*\.(.*)$/$i.\L$1/; s/jpeg$/jpg/' *.{jpg,JPG,jpeg,JPEG,png,PNG,gif,GIF}. You don't need the shell loop since Perl can do the counting, and you don't need nullglob because rename ignores nonexistent file names. –  Gilles Feb 16 '11 at 0:10
    
Thanks, I didn't know rename could understand other (besides s/// and y///) perl commands too. –  marco Feb 16 '11 at 20:33

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.