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
  • 66,199
  • 35
  • 114
  • 250
Gmans
  • 1
  • 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
  • 35,316
  • 26
  • 130
  • 258
  • 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
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
frams
  • 516
  • 5
  • 17
  • This will not handle whitespace in filenames gracefully. And adding `-f` is *not* called for. – Wildcard Oct 14 '16 at 02:20
  • Also see: [Why does my shell script choke on whitespace or other special characters?](http://unix.stackexchange.com/q/131766/135943) – Wildcard Oct 14 '16 at 02:28