I didn't write the script I'm about to paste, I found it and modified it slightly because I don't know how to do it myself. Here is the current code:
for F in *.jpg *.gif ; do
identify "$F"
done | awk '{ split($3, wh, /x/); } wh[1] < 800 && wh[2] < 800 { print $1 }'
This works and displays images with dimensions less than 800px in either dimension. But if I try to change it to this:
for F in *.jpg *.gif ; do
identify "$F"
done | awk '{ split($3, wh, /x/); } wh[1] < 800 && wh[2] < 800 { rm -vfr $1 }'
Nothing happens, nothing is deleted, why not?
rm is a shell command, not an awk command.
One way to do what you want is to use awk just to print the file names (which it can do) and then pipe that into something that's capable of deleting:
for F in *.jpg *.gif ; do
identify "$F"
done | awk '{split($3,wh,/x/);} wh[1]<800 && wh[2]<800 {print $1}' | xargs rm
I haven't checked whether any of your other code is valid, I'm assuming it is because the script was working before you made your changes.
xargs will receive a list of things on its standard input and batch them up to have a specific command run against them. So, for example, the following sequence:
touch paxjunk001
touch paxjunk002
echo paxjunk* | xargs rm
will effectively be the same as:
touch paxjunk001
touch paxjunk002
rm paxjunk001 paxjunk002
Getting it to handle the "weird" file names such as those with spaces in them, is a matter of using NUL characters as the separator rather than white space.
That means your awk print command will turn into something like:
{ printf "%s\0", $1 }`
to get the filenames separated correctly, and using:
xargs --null
to ensure xargs understands the format.
If you're using ImageMagick, you can defer to identify the test about the size of your image. The -format switch to identify is very powerful and allows a lot of computations to be done.
For example:
identify -format '%[fx:w<800 && h<800]' image.jpg
will output to stdout 1 if the image has a width less than 800px and a height less than 800px, and outputs 0 otherwise. Using this is much safer than your solution of parsing the raw output of identify, since your solution breaks as soon as a filename contains a space.
I would suggest using something along these lines instead:
#!/bin/bash
shopt -s nullglob
for f in *.jpg *.gif; do
a=$(identify -format '%[fx:w<800 && h<800]' -- "$f") || continue
if [[ $a = 1 ]]; then
echo rm -v -- "$f"
fi
done
This will only echo the rm commands, and will not perform them. Remove the echo command in front of rm if you're happy with what you see.
For more information about these features of ImageMagick, please see these links:
fx operator.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With