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

例如,在1个文件上运行命令:

$ cmd [option] [filename] > results.out

当前回答

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

其他回答

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

sh /dir/* > ./result.txt

你可以使用xarg:

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

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

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

Maxdepth

我发现它很适合Jim Lewis的答案,只需要添加一点这样的内容:

$ export DIR=/path/dir && cd $DIR && chmod -R +x *
$ find . -maxdepth 1 -type f -name '*.sh' -exec {} \; > results.out

排序顺序

如果你想按排序顺序执行,可以这样修改:

$ export DIR=/path/dir && cd $DIR && chmod -R +x *
find . -maxdepth 2 -type f -name '*.sh' | sort | bash > results.out

举个例子,它将按照以下顺序执行:

bash: 1: ./assets/main.sh
bash: 2: ./builder/clean.sh
bash: 3: ./builder/concept/compose.sh
bash: 4: ./builder/concept/market.sh
bash: 5: ./builder/concept/services.sh
bash: 6: ./builder/curl.sh
bash: 7: ./builder/identity.sh
bash: 8: ./concept/compose.sh
bash: 9: ./concept/market.sh
bash: 10: ./concept/services.sh
bash: 11: ./product/compose.sh
bash: 12: ./product/market.sh
bash: 13: ./product/services.sh
bash: 14: ./xferlog.sh

无限的深度

如果你想在特定条件下无限深度执行,你可以使用这个:

export DIR=/path/dir && cd $DIR && chmod -R +x *
find . -type f -name '*.sh' | sort | bash > results.out

然后把子目录中的每个文件放在上面,就像这样:

#!/bin/bash
[[ "$(dirname `pwd`)" == $DIR ]] && echo "Executing `realpath $0`.." || return

在父文件主体的某个地方:

if <a condition is matched>
then
    #execute child files
    export DIR=`pwd`
fi

这个怎么样:

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顺序(虽然我可能是错的),这可能不是什么 你想要的。