This question pertains to the situation where
mypicture.jpg
mypicture-300x500.jpg
and mypicture-600x1000.jpg
In this scenario, the remaining photos on the filesystem are mypicture-300x500.jpg
and mypicture-600x1000.jpg
.
How can you script this to find these "dangling" images with the missing original and delete the "dangling" images.
I've written a Bash script that will attempt to find the original filename (ie mypicture.jpg
) based on scraping away the WordPress resolution (ie mypicture-300x500.jpg
), and if it's not found, delete the "dangling image" (ie rm -f mypicture-300x500.jpg
)
#!/bin/bash
for directory in $(find . -type d)
do
for image in $(ls $directory)
do
echo "The current filename is $image"
resolution=$(echo $image | rev | cut -f 1 -d "-" | rev | xargs)
echo "The resolution is $resolution"
extension=$(echo $resolution | rev| cut -f 1 -d "." | rev | xargs)
echo "The extension is $extension"
resolutiononly=$(echo $resolution | sed "s@.$extension@@g")
echo "The resolution only is $resolutiononly"
pattern="[0-9]+x[0-9]+"
if [[ $resolutiononly =~ $pattern ]]; then
echo "The pattern matches"
originalfilename=$(echo $image | sed "s@-$resolution@.$extension@g")
echo "The current filename is $image"
echo "The original filename is $originalfilename"
if [[ -f "$originalfilename" ]]; then
echo "The file exists $originalfilename"
else
rm -f $directory/$image
fi
else
break
fi
done
done
You could use find
:
$ find . -type f -regex '.*/mypicture-[0-9]+x[0-9]+\.jpg'
This will print a list of files. Check that it is correct and then, instead of printing the names of the files, tell find
to delete them:
$ find . -type f -regex '.*/mypicture-[0-9]+x[0-9]+\.jpg' -exec rm -f {} \;
See man find
for the explanation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.