2

I have a simple need to recursively find and delete files of a certain extension. So I have syntax that will find and remove the files and pipe them into xargs -0 rm, but I can't seem to create a log of the files that were removed.

What I have so far:

find /var/www/html -type f -regex ".*/.*\.(png|jpg)" -print0 |xargs -0 rm
  • 1
    What do you mean by "log"? What does your script do exactly? Please edit your question and show us a minimal example of the script and the kind of log you would like it to produce. – terdon Nov 1 '15 at 22:47
  • find /var/www/html -type f -regex ".*/.*\.(png|jpg)" -print0 |xargs -0 rm – user189395 Nov 1 '15 at 22:57
  • I'd like to send stdout and stderr to a file, is all. – user189395 Nov 1 '15 at 22:58
  • Do you mean that you want to list the names of the files deleted as they are being removed? – DarkHeart Nov 1 '15 at 22:58
  • Yes, or a list of deleted files. – user189395 Nov 1 '15 at 23:04
2

rm is normally silent when deleting files. If you want to create a log showing files removed, add the -v option. Thus, replace:

xargs -0 rm

with:

xargs -0 rm -v >log
1

You can use find itself to delete files, and at the same time to write their names to stdout:

find /var/www/html -type f -regex ".*/.*\.\(png\|jpg\)" -delete -print >logfile

Note: Order of -delete and -print options is important. Second option will only be applied if first returns true, i.e. if first -delete option could not delete file, then its name will not be printed to stdout. If you put -print first, then it will put the filename to stdout regardless of whether -delete could really delete the file.

Note2: I had to escape brackets and vertical line to make regex work by default with my system's find util. Alternatively, you can specify -regextype to posix-egrep, for example. Anyway, it worth first trying find command w/o -delete option to check whether it correctly finds files:

find /var/www/html -type f -regex ".*/.*\.\(png\|jpg\)" -print

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.