Suppose I have a directory with files and subdirectories underneath it. Some of the files contain a pattern "^File:" in their contents.

Is there some way I can use grep and a bash command to remove files that contain this pattern? Note I am talking about contents of the file, not the filenames.

  • This question might be better for unix.stackexchange.com
    – Hemm
    Commented Oct 27, 2011 at 23:37
  • If you could narrow your search by a filename pattern, then you'd get a lot better efficiency from any scripts you get.
    – Chris Ting
    Commented Oct 27, 2011 at 23:43

3 Answers 3


A simple piped find should suffice (caveat emptor, I haven't tested this against a large set of data -- backup anything important):

find /path/to/dir -type f -exec egrep -Il '^File:' {} \;|xargs rm -fv
  • @Hemm -- Actually I tested mine against files with spaces and it removes them just fine. You probably want to add -I to your grep or he'll be deleting binary files too.
    – Garrett
    Commented Oct 28, 2011 at 0:24
  • @Hemm's example can also potentially run into argument limitations of grep if too many files are matched by the wildcard.
    – Garrett
    Commented Oct 28, 2011 at 0:33
  • I tested mine on 100k+ files containing the string with no problems. And I already have -l in it.
    – Hemm
    Commented Oct 28, 2011 at 1:54
  • 1
    I as in India. man grep ;)
    – Garrett
    Commented Oct 28, 2011 at 2:31
  • 1
    -I- blame sans serif.
    – Hemm
    Commented Oct 28, 2011 at 2:59
grep -rlI "meow" * | xargs -I{} rm -v {} 

The above code removes files containing meow.

This also handles cases where there are filenames with spaces and other characters. xargs rm -f alone, as suggested in other answers, will fail.

  • 1
    That doesn't descend into subdirectories. Commented Oct 28, 2011 at 0:07
  • Whoops. -r added.
    – Hemm
    Commented Oct 28, 2011 at 0:14

Here's a one-liner.

grep -r "^File:" /path/to/directory | cut -d: -f1 | sort | uniq | xargs rm -f
  • Much more verbose than it needs to be. Use grep's -l option to list just the file names. The sort and uniq steps are unnecessary, since the files are just going to be deleted. grep -r -l "^File:" /path/to/directory | xargs rm -f. Or, if some of the file names might contain funny characters (particularly spaces): grep -r -l "^File:" /path/to/directory | tr '\n' '\0' | xargs -0 rm -f. (I have not tested these; try xargs echo rm -f first to make sure it's generating the right list of files.) Commented Oct 28, 2011 at 0:06
  • @ChrisTing: Could you provide some explanation about what your code does? Commented Nov 1, 2011 at 1:34
  • @KeitThompson: Could you please consider to copy that in an own answer? :) Commented Nov 1, 2011 at 1:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .