如何使用>在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的不喜欢双引号。如果我删除了双引号,但是,那么命令会将整个命令到名为{}。出来,而不是一系列单个文件的单个文件的输出。
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. What you need to do, is this:
sh -c 'grep ABC "$1" > "$1.out"' -- {}
适用于的xargs
以及找到
。
顺便说一句,从来不使用xargs的,而不 -0
选项(除非非常罕见的,控制一次性交互使用你在哪里不担心破坏你的数据)。
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
。永远。用匹配或找到
而不是: http://mywiki.wooledge.org/ParsingLs一>
Also don't parse ls
. Ever. Use globbing or find
instead: http://mywiki.wooledge.org/ParsingLs
使用找到
对于需要递归和一个简单的循环与一切一水珠的一切:
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
注意正确使用引号。
Notice the proper use of quotes.
这篇关于如何使用>在xargs命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!