谁能提供一下代码来完成以下工作。 假设有一个文件目录,所有这些文件都需要通过一个程序运行。该程序将结果输出到标准输出。我需要一个脚本,它可以进入一个目录,在每个文件上执行命令,并将输出连接到一个大的输出文件。
例如,在1个文件上运行命令。
$ cmd [option] [filename] > results.out
下面的bash代码将把$file传递给命令,其中$file将代表/dir中的每个文件
for file in /dir/*
do
cmd [option] "$file" >> results.out
done
例子
el@defiant ~/foo $ touch foo.txt bar.txt baz.txt
el@defiant ~/foo $ for i in *.txt; do echo "hello $i"; done
hello bar.txt
hello baz.txt
hello foo.txt
这样吧。
find /some/directory -maxdepth 1 -type f -exec cmd option {} \; > results.out
-maxdepth 1
参数可以防止find递归到
任何子目录。 (如果你想处理这些嵌套目录,你可以省略这个参数。)-type -f
指定只处理普通文件。-exec cmd option {}
告诉它用指定的option
对找到的每个文件运行cmd
,文件名用{}
代替。/;
表示命令的结束。cmd
执行的输出被重定向到
results.out
。然而,如果你关心文件被处理的顺序,你最好写一个循环。
你可能最好写一个循环。 我认为find
是按编码顺序处理文件的
我认为find
是按照节点顺序来处理文件的(尽管我可能是错的),这可能不是你想要的
你想要的。
基于@Jim Lewis'的方法。
这里有一个快速的解决方案,使用find
,也可以按修改日期对文件进行排序。
$ find directory/ -maxdepth 1 -type f -print0 | \
xargs -r0 stat -c "%y %n" | \
sort | cut -d' ' -f4- | \
xargs -d "\n" -I{} cmd -op1 {}
关于排序见。
http://www.commandlinefu.com/commands/view/5720/find-files-and-list-them-sorted-by-modification-time