Reputation: 3092
I can convert an image like this:
convert -resize 50% foo.jpg foo_50.jpg
How can I automate such a command to convert all the images in a folder?
You can assume every image has .jpg
extension.
A solution easily adaptable to automate the conversion of all the images inside the subdirectories of the working directory is preferable.
Upvotes: 0
Views: 89
Reputation: 52132
You can use find -exec
:
find -type f -name '*.jpg' -exec \
bash -c 'convert -resize 50% "$0" "${0%.jpg}"_50.jpg' {} \;
find -type f -name '*.jpg'
finds all .jpg
files (including those in subdirectories) and hands it to the command after -exec
, where it can be referenced using {}
.
Because we want to use parameter expansion, we can't use -exec convert -resize
directly; we have to call bash -c
and supply {}
as a positional parameter to it ($0
inside the command). \;
marks the end of the -exec
command.
Upvotes: 1
Reputation: 1731
You can also try this (less elegant) one-liner using ls+awk:
ls *.jpg | awk -F '.' '{print "convert -resize 50% "$0" "$1"_50.jpg"}' | sh
this assumes that all the .jpg files are in the current directory. before running this, try to remove the | sh
and see what is printed on the screen.
Upvotes: 0
Reputation: 241868
You can use a for loop with pattern expansion:
for img in */*.jpg ; do
convert -resize 50% "$img" "${img%.jpg}"_50.jpg
done
${variable%pattern}
removes the pattern from the right side of the $variable.
Upvotes: 3