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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With