4

I want to remove all texts that include string foo.

I can list all files by ack-grep foo, but I couldn't find a way to remove all files like -exec rm {} option like find.

How can I delete all files that contains particular string?

ironsand
  • 5,085
  • 12
  • 50
  • 73

2 Answers2

6

With GNU xargs:

ack -l --print0 foo | xargs -r0 rm --

ack's --print0 and xargs' -0 cause ack and xargs to write and read using NUL as the delimiter, which guarantees proper filename handling. Without it, xargs will accept a far more wide range of characters as a delimiter.

Chris Down
  • 122,090
  • 24
  • 265
  • 262
2

You can use option -l with grep and ack which lists only filename:

grep -l --null foo ./* | xargs -r0 rm

or:

ack -l --print0 foo ./* | xargs -r0 rm --
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
taliezin
  • 9,085
  • 1
  • 34
  • 38
  • This is dangerous, any filenames containing whitespace will be handled improperly, and could cause unexpected files to be removed. – Chris Down Apr 01 '15 at 09:44
  • There could be problems with `grep` and `rm` if a directory is included in the search directory – A.B. Apr 01 '15 at 09:46