如何使用 >在 xargs 命令中? [英] How to use > in an xargs command?
问题描述
我想找到一个 bash 命令,它可以让我 grep 目录中的每个文件,并将该 grep 的输出写入一个单独的文件.我的猜测是做这样的事情
I want to find a bash command that will let me grep every file in a directory and write the output of that grep to a separate file. My guess would have been to do something like this
ls -1 | xargs -I{} "grep ABC '{}' > '{}'.out"
但是,据我所知,xargs 不喜欢双引号.但是,如果我删除双引号,则该命令会将整个命令的输出重定向到名为{}".out 的单个文件,而不是一系列单独的文件.
but, as far as I know, xargs doesn't like the double-quotes. If I remove the double-quotes, however, then the command redirects the output of the entire command to a single file called '{}'.out instead of to a series of individual files.
有谁知道使用 xargs 做到这一点的方法吗?我只是以这个 grep 场景为例来说明我的 xargs 问题,因此任何不使用 xargs 的解决方案都不适用于我.
Does anyone know of a way to do this using xargs? I just used this grep scenario as an example to illustrate my problem with xargs so any solutions that don't use xargs aren't as applicable for me.
推荐答案
不要犯这样的错误:
sh -c "grep ABC {} > {}.out"
这在很多情况下都会中断,包括时髦的文件名,并且不可能正确引用.您的 {}
必须始终是命令的一个完全独立的参数,以避免代码注入错误.你需要做的是:
This will break under a lot of conditions, including funky filenames and is impossible to quote right. Your {}
must always be a single completely separate argument to the command to avoid code injection bugs. What you need to do, is this:
xargs -I{} sh -c 'grep ABC "$1" > "$1.out"' -- {}
适用于 xargs
以及 find
.
顺便说一句,不要在没有 -0
选项的情况下使用 xargs(除非用于非常少见且受控的一次性交互式使用,您不必担心破坏数据).
By the way, never use xargs without the -0
option (unless for very rare and controlled one-time interactive use where you aren't worried about destroying your data).
也不要解析ls
.曾经.使用通配符或 find
代替:http://mywiki.wooledge.org/ParsingLs
Also don't parse ls
. Ever. Use globbing or find
instead: http://mywiki.wooledge.org/ParsingLs
对于需要递归的所有内容使用 find
,对于其他所有内容使用带有 glob 的简单循环:
Use find
for everything that needs recursion and a simple loop with a glob for everything else:
find /foo -exec sh -c 'grep "$1" > "$1.out"' -- {} ;
或非递归:
for file in *; do grep "$file" > "$file.out"; done
注意引号的正确使用.
这篇关于如何使用 >在 xargs 命令中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!