Ubuntu covert all images in a folder

2019-06-11 17:23发布

问题:

I am using a script for converting all the images in my folder to flop operation. The script is like this:

for f in *.jpg; do
    new="${f%%.jpg}_flop.jpg";
    convert "$f" -flop -quality 100 "$new";
 done

Now I have found that there may be also images with the extension .JPG I thought of adding a new for loop that looks like this:

for f in *.JPG; do
    new="${f%%.jpg}_flop.jpg";
    convert "$f" -flop -quality 100 "$new";
 done

I think that there is a syntax for ignoring the case, and this way I can do a single loop instead of 2, any help?

More, if there will also be the extensions .jpeg or .JPEG, is there a syntax for this, too?

回答1:

You can simply do

for f in *.jpg *.JPG; do
    ...

If you want a single expression, you can use the extglob extension in Bash.

set -o extglob
for f in *.@(JP@(|E)G|jp@(|e)g); do
    ...

To make globbing case insensitive, you can shopt -s nocaseglob but there is no particular syntax to make a single glob expression case-insensitive.

You could also use the slightly imprecise

for f in *.[Jj][Pp][Gg] *.[Jj][Pp][Ee][Gg]; do
    ...

to match case-insensitively.



回答2:

Something along these lines:

#/bin/bash
shopt -s nullglob                # don't give error messages if no matching files
shopt -s nocaseglob              # ignore case
for f in *.jpg *.jpeg; do

   new=${f/.[Jj][Pp][Ee][Gg]/}      # strip extension
   new=${new/.[Jj][Pp][Gg]/}        # whether JPEG or jpg
   new="$new_flop.jpg"

   convert "$f" -flop -quality 100 "$new"
done


回答3:

I have a script that does something similar:

for file in {*.jpg,*.JPG}; do
  mv "$file" "old$file"
  convert -resize 3000000@\> "old$file" -quality 80 "$file"
  rm "old$file"
done

I also made a video explaining it: https://www.youtube.com/watch?v=AG0bItQLBdI



回答4:

for f in `ls * | grep -i "jp[e]\?g$"`;do
   new="${f%%.jpg}_flop.jpg";     
   echo convert "$f" -flop -quality 100 "$new";  
done

Regular expressions are your friend.