有人能提供代码来做以下工作吗: 假设有一个文件目录,所有这些文件都需要通过一个程序运行。程序将结果输出到标准输出。我需要一个脚本,它将进入一个目录,对每个文件执行命令,并将输出连接到一个大输出文件。

例如,在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

其他回答

我认为简单的解决方法是:

sh /dir/* > ./result.txt

下面的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

你可以使用xarg:

ls | xargs -L 1 -d '\n' your-desired-command 

-L 1导致一次传递一个项目 -d '\n'根据换行拆分ls的输出。

我在树莓派的命令行中运行:

for i in *; do cmd "$i"; done

基于@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