Convert every file from JPEG to GIF in terminal

I have work with find before to find all specific files in a folder and subfolder and do something about it

For example, I did use

find /folder/ -name '*.txt' -exec chmod 666 {} \;

This code to easy change write access to every text file in the folder.

Now I was going to try to convert every jpg(even JPG) to gif in the same way but not sure if that is so easy. When I try with the convert command tools it wants to have an inputfilename and output filename but I do not think find give that so maybe find is not the right Tools to use?


Solution 1:

Find can be used for this, but I find it easier to use the shell instead. If your files are all in the same directory (no subdirectories) you can just do:

for f in /path/to/dir/*jpg /path/to/dir/*JPG; do
    convert "$f" "${f%.*}.gif"
done

The ${var%something} syntax will remove the shortest match for the glob something from the end of the variable $var. For example:

$ var="foo.bar.baz"
$ echo "$var : ${var%.*}"
foo.bar.baz : foo.bar

So here, it is removing the final extension from the filename. Therefore, "${f%.*}.gif" is the original file name but with .gif instead of .jpg or .JPG.

If you do need to recurse into subdirectories, you can use bash's globstar option (from man bash):

globstar
    If set, the pattern ** used in a pathname expansion con‐
    text will match all files and zero or  more  directories
    and  subdirectories.  If the pattern is followed by a /,
    only directories and subdirectories match.

You can enable it with shopt -s globstar:

shopt -s globstar
for f in /path/to/dir/**/*jpg /path/to/dir/**/*JPG; do
    convert "$f" "${f%.*}.gif"
done

Solution 2:

You can indeed use find - with a shell wrapper that calls the appropriate convert command and generates the output file using paramemter substitution. Ex.

find . -name '*.jpg' -execdir sh -c '
  for f; do convert -verbose "$f" "${f%.*}.gif"; done
' find-sh {} +

Change -name to -iname to include the .JPG extension (although note that the replacement .gif extension will be lower case regardless).