How to use > in an xargs command?

后端 未结 3 1103
长情又很酷
长情又很酷 2020-12-02 03:47

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

3条回答
  •  甜味超标
    2020-12-02 04:34

    Do not make the mistake of doing this:

    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"' -- {}
    

    Applies to xargs as well as find.

    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).

    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"' -- {} \;
    

    or non-recursive:

    for file in *; do grep "$file" > "$file.out"; done
    

    Notice the proper use of quotes.

提交回复
热议问题