Here’s a common problem. You untar an archive and it contains a large number of files that end .jpeg. You need them to have a .jpg extension. At first glance, you might be tempted to try this:
mv *.jpeg *.jpg
Give it a try and you will find it doesn’t work. The correct way to change the extension is to iterate over all of the files. Let’s start with the following:
dcolon@dcolonbuntu:/tmp/foobar$ ls
friday.jpeg monday.jpeg Saturday.jpeg sunday.jpeg Thursday.jpeg Tuesday.jpeg WEDNESDAY.jpeg
dcolon@dcolonbuntu:/tmp/foobar$
Once in the loop, you need to save the filename before the extension. I use a temporary variable and awk to extract it.
Here is my solution:
dcolon@dcolonbuntu:/tmp/foobar$ for i in *.jpeg
> do
> basefilename=$(echo $i | awk -F.jpeg '{print $1}')
> mv "$i" "$basefilename.jpg"
> done
dcolon@dcolonbuntu:/tmp/foobar$ ls
friday.jpg monday.jpg Saturday.jpg sunday.jpg Thursday.jpg Tuesday.jpg WEDNESDAY.jpg
dcolon@dcolonbuntu:/tmp/foobar$
I use double quotes around the variable names to compensate for filenames with spaces. In the awk statement I use the entire replacement pattern as my field separator. Using -F. will fail if you have a filename like foo.bar.jpeg.