使用 find -exec 重定向标准输出而不创建新的 shell [英] Redirecting stdout with find -exec and without creating new shell
问题描述
我有一个脚本,它只将数据写入stdout
.我需要为多个文件运行它并为每个输入文件生成一个不同的输出文件,我想知道如何使用 find -exec
.所以我基本上尝试了几个变体(我用 cat
替换了脚本,只是为了可测试性):
I have one script that only writes data to stdout
. I need to run it for multiple files and generate a different output file for each input file and I was wondering how to use find -exec
for that. So I basically tried several variants of this (I replaced the script by cat
just for testability purposes):
find * -type f -exec cat "{}" > "{}.stdout" ;
但无法使其工作,因为所有数据都被写入一个字面命名为{}.stdout
的文件.
but could not make it work since all the data was being written to a file literally named{}.stdout
.
最终,我可以让它工作:
Eventually, I could make it work with :
find * -type f -exec sh -c "cat {} > {}.stdout" ;
虽然这个最新的表单与 cat
配合得很好,但我的脚本需要通过几个初始化脚本加载环境变量,因此我最终得到:
But while this latest form works well with cat
, my script requires environment variables loaded through several initialization scripts, thus I end up with:
find * -type f -exec sh -c "initscript1; initscript2; ...; myscript {} > {}.stdout" ;
这似乎很浪费,因为我已经在当前的 shell 中初始化了所有内容.
Which seems a waste because I have everything already initialized in my current shell.
使用 find
有没有更好的方法来做到这一点?欢迎使用其他单线.
Is there a better way of doing this with find
? Other one-liners are welcome.
推荐答案
一个简单的解决方案是在脚本周围放置一个包装器:
A simple solution would be to put a wrapper around your script:
#!/bin/sh
myscript "$1" > "$1.stdout"
将其命名为 myscript2
并使用 find 调用它:
Call it myscript2
and invoke it with find:
find . -type f -exec myscript2 {} ;
请注意,尽管 find 的大多数实现都允许您执行已完成的操作,但从技术上讲,如果您在 的参数列表中多次使用
.{}
,则 find 的行为是未指定的 -执行
Note that although most implementations of find allow you to do what you have done, technically the behavior of find is unspecified if you use {}
more than once in the argument list of -exec
.
这篇关于使用 find -exec 重定向标准输出而不创建新的 shell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!