8

I have a directory and some of the files' extensions are in uppercase (.JPG) instead of lowercase.

I want to make sure every file has .jpg as its extension. How would I do this from a shell prompt?

2
  • It's a shame that linux doesn't have AppleScript.
    – gadgetmo
    Feb 13, 2012 at 18:42
  • 2
    Its so great that Linux has no AppleScript.
    – math
    Feb 14, 2012 at 20:54

5 Answers 5

15

Using Shell Parameter Expansion:

for f in *.JPG; do
    mv "${f}" "${f%%.JPG}.jpg"
done

The " characters will take care of filenames containing spaces, as photographs often do.

4
  • 5
    +1 This solution works even if you have spaces in the filename, but you mean "$f" instead of "f". Feb 8, 2012 at 11:06
  • Shell Parameter Expansion is a bit cryptic, one could use basename instead: for f in *.JPG; do mv "$f" "`basename $f .JPG`.jpg"; done
    – math
    Feb 14, 2012 at 21:02
  • @math: I prefer my version as it works with filenames containing whitespace and will also work with /path/to/*.JPG. You're welcome to submit your own answer, of course :)
    – johnsyweb
    Feb 14, 2012 at 21:17
  • Of course basename will strip of leading directories but will work with spaces inside filenames. (I don't think this is worth of an answer ;) so I posted it as a comment)
    – math
    Feb 14, 2012 at 21:25
10

If you can use external tools (not only bash), check rename command!

rename .JPG .jpg *

The rename is part of util-linux.

2
  • rename is... problematic. There's a version of rename that comes with perl that accepts different arguments to do the same thing.
    – cha0site
    Feb 13, 2012 at 11:04
  • Could you explain a bit more? Which version BTW?
    – math
    Feb 14, 2012 at 20:55
3

If you do have spaces in filenames:

for f in *.JPG; do [[ -f "${f}" ]] && mv "${f}" "${f/%JPG/jpg}"; done
2

I would suggest to have a look at the mmv command. It's suited exactly for this kind of tasks. In your scenario it would be:

#> mmv "*.JPG" "#1.jpg"

The man page is full of examples, so it takes no time to get used to it.

On Debian systems it can be installed with:

#> aptitude install mmv
0

if you don't have spaces in the filenames:

for f in *.JPG; do mv $f `echo $f | sed 's/JPG$/jpg/'`; done
3
  • 1
    It'd be easy enough to make this work for files with spaces in the name: just add double quotes around both arguments to mv. Feb 8, 2012 at 11:09
  • I don't have spaces. What do I add to make this happen in the CURRENT directory. At the moment I get error - mv: cannot stat `*.JPG': No such file or directory
    – Mark Flint
    Feb 8, 2012 at 11:26
  • 1
    you don't have any JPGs there. Feb 8, 2012 at 11:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .