有人能提供代码来做以下工作吗: 假设有一个文件目录,所有这些文件都需要通过一个程序运行。程序将结果输出到标准输出。我需要一个脚本,它将进入一个目录,对每个文件执行命令,并将输出连接到一个大输出文件。
例如,在1个文件上运行命令:
$ cmd [option] [filename] > results.out
有人能提供代码来做以下工作吗: 假设有一个文件目录,所有这些文件都需要通过一个程序运行。程序将结果输出到标准输出。我需要一个脚本,它将进入一个目录,对每个文件执行命令,并将输出连接到一个大输出文件。
例如,在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
其他回答
基于@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
这个怎么样:
find /some/directory -maxdepth 1 -type f -exec cmd option {} \; > results.out
-maxdepth 1参数防止find函数递归降为 任何子目录。(如果你想处理这样的嵌套目录,你可以省略这个。) -type -f指定只处理普通文件。 -exec CMD选项{}告诉它对找到的每个文件使用指定选项运行CMD,文件名替换为{} \;表示命令的结束。 最后,所有单个cmd执行的输出被重定向到 results.out
但是,如果您关心文件处理的顺序,则可以使用 也许写个循环会更好。我认为find处理文件 在inode顺序(虽然我可能是错的),这可能不是什么 你想要的。
我在树莓派的命令行中运行:
for i in *; do cmd "$i"; done
下面的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
我认为简单的解决方法是:
sh /dir/* > ./result.txt