10

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)

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
uhhhhhhhhhh_
  • 103
  • 1
  • 1
  • 5
  • 1
    https://unix.stackexchange.com/questions/167823/find-exec-rm-vs-delete – Stephen Rauch Jun 22 '17 at 00:23
  • 3
    You don't need a pipe, you need the `-exec` or `-delete` primaries of `find`. Also see [Why is looping over find's output bad practice?](http://unix.stackexchange.com/q/321697/135943) – Wildcard Jun 22 '17 at 02:32
  • @Wildcard , Thankyou, I realised that find had a -delete primary when I was reading through the man find command. – uhhhhhhhhhh_ Jun 23 '17 at 00:11

1 Answers1

15

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
Viatorus
  • 105
  • 5