[SWLUG] BMP to JPG

justin at discordia.org.uk justin at discordia.org.uk
Sat Apr 26 11:53:22 UTC 2003


On 26 Apr, Julian Hall wrote:
> 1.  With option 2 quoted below, could you use a wildcard, for example:
> 
> cjpeg *.bmp > *.jpg
> 
> Thereby converting a whole directory of files in one sweep?

Unfortunately not, in Linux (and all unix like systems) the command
shell expands the wildcards before the program gets run.
(There are some exceptions, where if you are careful to hand the
wildcard through to the program it will do something special with it)

Which means, if you had for example the following files in your
directory:  one.bmp two.bmp three.bmp test.jpg failed.jpg

then you command line would expand to
cjpeg one.bmp two.bmp three.bmp > test.jpg failed.jpg

which would obviously not be what you required.

The trick is to step through the filenames one at a time, there are
various ways to do this, but my favourite is to the 'for'

for i in *.bmp
do
...
done

will set the contents of the $i variable to be in turn each word (and
thus filename) on the rest of the line. and run the contents ... for
each setting.  If we combine this with a short commands to strip the
.bmp ending off the filename and attach a .jpg one, we get this:

for i in *.bmp
do
NEW=`basename $i .bmp`.jpg
echo "Converting $i to $NEW"
cjpeg $i > $NEW
done


This is a general unix philosophy, each program is (usually) a very
simple little tool that does one task well, and it is easy to use these
tools in combination to achieve more complex tasks.
thus the image conversion program is not burdened with needing to know
about wildcards because something else already does that.
This is what makes it a very powerful system, but also what can make it
a little daunting for a beginner or those used to monolithic systems.






More information about the Swlug mailing list