bash 如何使用grep和rm删除文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31779632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove files using grep and rm?
提问by PRK
grep -n magenta *| rm *
grep: a.txt
: No such file or directory
grep: a.txt
: 无此文件或目录
grep: b
: No such file or directory
grep: b
: 无此文件或目录
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?
此外,尝试过grep magenta * -exec rm '{}' \;
但没有运气。任何的想法?
回答by John1024
Use xargs
:
使用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.
xargs 的目的是在 stdin 上获取输入并将其放置在其参数的命令行上。
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 manor of filename to be handled safely.The
-0
option to xargs to treat its input as NUL-separated.
该
-l
选项告诉 grep 不要打印匹配的文本,而是只打印包含匹配文本的文件的名称。该
--null
选项告诉 grep 用 NUL 字符分隔文件名。这允许安全处理所有文件名庄园。该
-0
选项xargs的对待其输入为NUL分隔。
回答by SriniV
grep -lr magenta . | xargs -0 rm -f --
-l
prints file names of files matching the search pattern.-r
performs a recursive search for the patternmagenta
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 fromgrep
torm -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-
.
-l
打印与搜索模式匹配的文件的文件名。-r
magenta
对给定目录中的模式执行递归搜索.
。?如果这不起作用,请尝试-R
。(即,作为多个名称而不是一个)。xargs -0
将文件名从grep
到rm -f
--
经常被遗忘,但标记选项的结尾并允许删除名称以-
.
If you would like to see which files are about to be deleted, simply remove the | xargs -0 rm -f --
part.
如果您想查看将要删除哪些文件,只需删除该| xargs -0 rm -f --
部分即可。