Shell 脚本:将 bash 与 xargs 结合使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1590297/
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
Shell Scripting: Using bash with xargs
提问by Dan Monego
I'm trying to write a bash command that will delete all files matching a specific pattern - in this case, it's all of the old vmware log files that have built up.
我正在尝试编写一个 bash 命令,该命令将删除与特定模式匹配的所有文件 - 在这种情况下,它是所有已建立的旧 vmware 日志文件。
I've tried this command:
我试过这个命令:
find . -name vmware-*.log | xargs rm
However, when I run the command, it chokes up on all of the folders that have spaces in their names. Is there a way to format the file path so that xargs passes it to rm quoted or properly escaped?
但是,当我运行该命令时,它会阻塞所有名称中包含空格的文件夹。有没有办法格式化文件路径,以便 xargs 将其传递给 rm 引用或正确转义?
回答by Emil Sit
Try using:
尝试使用:
find . -name vmware-*.log -print0 | xargs -0 rm
This causes find to output a null character after each filename and tells xargs to break up names based on null characters instead of whitespace or other tokens.
这会导致 find 在每个文件名后输出一个空字符,并告诉 xargs 基于空字符而不是空格或其他标记来分解名称。
回答by L.R.
Do not use xargs. Find can do it without any help:
不要使用 xargs。Find 无需任何帮助即可完成:
find . -name "vmware-*.log" -exec rm '{}' \;
find . -name "vmware-*.log" -exec rm '{}' \;
回答by Carl Norum
Check out the -0flag for xargs; combined with find's -print0you should be set.
检查-0标志xargs; 与find's-print0你应该被设置。
find . -name vmware-*.log -print0 | xargs -0 rm
回答by ghostdog74
GNU find
GNU 查找
find . -name vmware-*.log -delete
回答by rh0dium
find . -name vmware-*.log | xargs -i rm -rf {}
find . -name vmware-*.log | xargs -i rm -rf {}
回答by nkvnkv
find -iname pattern
use -inamefor pattern search
使用-iname的模式搜索
回答by Ray
To avoid space issue in xargs I'd use new line character as separator with -d option:
为了避免 xargs 中的空格问题,我将使用换行符作为带有 -d 选项的分隔符:
find . -name vmware-*.log | xargs -d '\n' rm

