Bash – Piping find results into another command

bashfindpipeshell-script

I'm trying to scan a file system for files matching specific keywords, and then remove them. I have this so far:

find . -iregex '.*.new.*' -regex '.*.pdf*'

How do I then pipe the result for this command into a remove command (such as rm)

Best Answer

One way is to expand the list of files and give it to rm as arguments:

$ rm $(find . -iregex '.*.new.*' -regex '.*.pdf*')

**That will fail with file names that have spaces or new lines.

You may use xargs to build the rm command, like this:

$ find . … … | xargs rm

** Will also fail on newlines or spaces

Or better, ask find to execute the command rm:

$ find . … … --exec rm {} \;

But the best solution is to use the delete option directly in find:

$ find . -iregex '.*.new.*' -regex '.*.pdf*' -delete
Related Question