Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove files using grep and rm?

Tags:

grep

bash

unix

grep -n magenta *| rm *

grep: a.txt: No such file or directory

grep: b: No such file or directory

Above command removes all files present in the directory except ., .. . It should remove only those files which contains the word "magenta"

Also, tried grep magenta * -exec rm '{}' \; but no luck. Any idea?

like image 452
PRK Avatar asked Aug 03 '15 04:08

PRK


People also ask

Can grep delete files?

To get rid of the unwanted error entries, you can use the UNIX® command grep. This command is available for Windows®, too. To do this, create a file that contains all patterns to be removed from the csserror. log.

How do I delete multiple files in rm?

Deleting multiple files To delete multiple files at once, simply list all of the file names after the “rm” command. File names should be separated by a space. With the command “rm” followed by multiple file names, you can delete multiple files at once.

Can you delete a file removed by the rm command?

To remove or delete a file or directory in Linux, FreeBSD, Solaris, macOS, or Unix-like operating systems, use the rm command or unlink command.


2 Answers

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.

like image 172
John1024 Avatar answered Sep 18 '22 15:09

John1024


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.

like image 21
SriniV Avatar answered Sep 19 '22 15:09

SriniV