How to remove files using grep and rm?

Use xargs:

grep -l --null magenta ./* | xargs -0 rm

The purpose of xargs is to take input on stdin and place it on the command line of its argument.

What the options do:

  • The -l option tells grep not to print the matching text and instead just print the names of the files that contain matching text.

  • The --null option tells grep to separate the filenames with NUL characters. This allows all manner of filenames to be handled safely.

  • The -0 option to xargs to treat its input as NUL-separated.


Here is a safe way:

grep -lr magenta . | xargs -0 rm -f --
  • -l prints file names of files matching the search pattern.
  • -r performs a recursive search for the pattern magenta in the given directory ..  If this doesn't work, try -R. (i.e., as multiple names instead of one).
  • xargs -0 feeds the file names from grep to rm -f
  • -- is often forgotten but it is very important to mark the end of options and allow for removal of files whose names begin with -.

If you would like to see which files are about to be deleted, simply remove the | xargs -0 rm -f -- part.

Tags:

Unix

Bash

Grep