Bash:如何遍历目录结构并执行命令? [英] Bash: how to traverse directory structure and execute commands?
问题描述
我已经将一个大文本文件拆分为多个较小的文本集,以进行我正在执行的性能测试.有许多这样的目录:
I have split a large text file into a number of sets of smaller ones for performance testing that i'm doing. There are a number of directories like this:
/home/brianly/output-02 (contains 2 files myfile.chunk.00 and myfile.chunk.01)
/home/brianly/output-04 (contains 4 files...)
/home/brianly/output-06 (contains 6 files...)
重要的是要注意,每个目录中的文件数量正在增加.我需要做的是针对输出目录中的每个文本文件运行一个可执行文件.该命令针对单个文件如下所示:
It's important to note that there is an increasing number of files in each directory. What I need to do is run an executable against each of the text files in the output directories. The command looks something like this against a single file:
./myexecutable -i /home/brianly/output-02/myfile.chunk.00 -o /home/brianly/output-02/myfile.chunk.00.processed
这里-i参数是输入文件,-o参数是输出位置.
Here the -i parameter is the input file and -o parameter is the output location.
在C#中,我遍历目录以获取每个文件夹中的文件列表,然后遍历它们以运行命令行.如何使用bash遍历这样的目录结构,并根据位置和该位置中的文件使用正确的参数执行命令?
In C# I'd loop over the directories get the list of files in each folder, then loop over them to run the commandlines. How do I traverse a directory structure like this using bash, and execute the command with the correct parameters based on the location and files in that location?
推荐答案
对于这种事情,我总是将 find 与 xargs 一起使用:
For this kind of thing I always use find together with xargs:
$ find output-* -name "*.chunk.??" | xargs -I{} ./myexecutable -i {} -o {}.processed
现在,由于您的脚本一次只处理一个文件,因此已经直接将 -exec (或 -execdir )与 find 一起使用提示,它同样有效,但是我习惯使用 xargs ,因为在一次输入对多个参数操作的命令时,效率通常要高得多.因此,这是一个牢牢抓住工作带的非常有用的工具,因此我认为应该提一下.
Now since your script processes only one file at a time, using -exec (or -execdir) directly with find, as already suggested, is just as efficient, but I'm used to using xargs, as that's generally much more efficient when feeding a command operating on many arguments at once. Thus it's a very useful tool to keep in one's utility belt, so I thought it ought to be mentioned.
这篇关于Bash:如何遍历目录结构并执行命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!