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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:23:33  来源:igfitidea点击:

How to remove files using grep and rm?

bashunixgrep

提问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 -loption tells grep not to print the matching text and instead just print the names of the files that contain matching text.

  • The --nulloption tells grep to separate the filenames with NUL characters. This allows all manor of filename to be handled safely.

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

  • -l选项告诉 grep 不要打印匹配的文本,而是只打印包含匹配文本的文件的名称。

  • --null选项告诉 grep 用 NUL 字符分隔文件名。这允许安全处理所有文件名庄园。

  • -0选项xargs的对待其输入为NUL分隔。

回答by SriniV

Here is a safe way:

这是一个安全的方法:

grep -lr magenta . | xargs -0 rm -f --
  • -lprints file names of files matching the search pattern.
  • -rperforms a recursive search for the pattern magentain the given directory ..? If this doesn't work, try -R. (i.e., as multiple names instead of one).
  • xargs -0feeds the file names from grepto 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 -.
  • -l打印与搜索模式匹配的文件的文件名。
  • -rmagenta对给定目录中的模式执行递归搜索.。?如果这不起作用,请尝试-R。(即,作为多个名称而不是一个)。
  • xargs -0将文件名从greprm -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 --部分即可。