0

I have a list of files in a directory and I need to remove every file that contains either a 0 or a 7. I feel like I need to use grep but I'm not too sure. Any ideas?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Gmans
  • 1
  • 1
    every file that contains either a 0 or a 7 ---> we have to check in filename or contents of file ? – Kamaraj Oct 14 '16 at 02:06

2 Answers2

1

What you want to do is evaluate your files according to a specific conditional test, and perform an action on each file according to the result of the conditional test. This is the exact purpose of the find command.

Here is a portable (POSIX-compliant) command to remove regular files that have a contents including a "0" or a "7":

find . -type f -exec grep -q '[07]' {} \; -exec rm {} +

Note that this recursively searches the current directory.

If that's not what you want, you can check if the -maxdepth primary is available (in which case you may as well use the primary -delete as well; neither is specified by POSIX):

find . -maxdepth 1 -type f -exec grep -q '[07]' {} \; -delete

Or, you could apply the techniques given in:

Wildcard
  • 36,499
  • If there's no requirement for recursion here this could be done a lot simpler with ls *[0,7]* (to verify what files match) and then rm -v *[0,7]*. Your answer is a lot fancier though. – pzkpfw Sep 16 '17 at 16:59
0
grep -l '[07]' DirToYourFiles/* | xargs rm -f

grep -l means list filenames only

[07] means either 0 or 7

xargs makes them a command.

That assumes file names don't contain blanks, newline, single quote, double quote or backslash characters. With GNU utilities, you can make it more reliable with:

grep -lZ '[07]' DirToYourFiles/* | xargs -r0 rm -f
frams
  • 546