When i run this find command:

find /html/car_images/inventory/ -type f -iname \*.jpg -mtime -4

i get output like this:


My goal is to delete a "thumbnail" folder that exists in each of these directories (ie delete this folder: /html/car_images/inventory/16128/thumbnails/ and also delete /html/car_images/inventory/16115/thumbnails/

I'm thinking perhaps of a script that takes each line of output from the above find command, then replaces " *.jpg " with "thumbnails" and adds as a prefix "rm -fr" such that i end up with this:

rm -fr /var/www/html/car_images/inventory/16115/thumbnails/
rm -fr /var/www/html/car_images/inventory/16128/thumbnails/

and so on...

Any ideas on how to do this? (maybe using the -exec option of find and sed or cut?)

(another way to phrase my entire goal is, if a folder contains a .jpg file that is "younger" than X days, than delete the "thumbnails" folder, in its folder)


Assuming you don't have filenames with newline(s):

find /html/car_images/inventory/ -type f -iname \*.jpg -mtime -4 \
     -exec sh -c 'echo "${1%/*}"' _ {} \; | sort -u | \
          xargs -d $'\n' -I{} rm -r {}/thumbnails
  • The parameter expansion, ${1%/*} extracts the portion without the filename from each found entry

  • sort -u sorts and then make the entries unique so that we don't have any duplicate

  • xargs -I{} rm -r {}/thumbnails adds thumbnails at the end, and then remove the resultant directory

  • Wow, thanks for that really fast, great answer, i think your code will do exactly my goal, however to test it i changed the last line: rm -r {}/thumbnails to echo {}/thumbnails ... hoping to get a list (to test before running with rm -r) , now maybe this is due to my change, but it only 'echos' a single directory , not several. is this because of the rm to echo change i made or would you code as is only remove a single directory (because it should be removing several depending upon the -mtime number) tks
    – James Gaul
    Oct 2 '16 at 5:33
  • @JamesGaul Ooops, my bad. Muscle memory caught me, check the edited version.
    – heemayl
    Oct 2 '16 at 5:40
  • wow, im just blown away by how quickly you came up with that initial answer! it works great! thank you!
    – James Gaul
    Oct 2 '16 at 5:42
  • @JamesGaul Glad i could help :)
    – heemayl
    Oct 2 '16 at 5:43
while read dir;
    rm -r "$dir"/thumbnails;
done < <(while read file; do dirname "$file"; done < <(find /html/car_images/inventory/ -type f -iname \*.jpg -mtime -4) | sort -u)

This is completed using a process substitution inside a process substitution.

It finds files based on OP criteria, gets dirname of each jpg file in a while loop, sorts and removes duplicates (inspired by @heemayl), then reads that in a while loop to remove the thumbnail directory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.