有人能提供代码来做以下工作吗: 假设有一个文件目录,所有这些文件都需要通过一个程序运行。程序将结果输出到标准输出。我需要一个脚本,它将进入一个目录,对每个文件执行命令,并将输出连接到一个大输出文件。
例如,在1个文件上运行命令:
$ cmd [option] [filename] > results.out
有人能提供代码来做以下工作吗: 假设有一个文件目录,所有这些文件都需要通过一个程序运行。程序将结果输出到标准输出。我需要一个脚本,它将进入一个目录,对每个文件执行命令,并将输出连接到一个大输出文件。
例如,在1个文件上运行命令:
$ cmd [option] [filename] > results.out
当前回答
我认为简单的解决方法是:
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
我在树莓派的命令行中运行:
for i in *; do cmd "$i"; done
一种快速而肮脏的方法有时可以完成工作:
find directory/ | xargs Command
例如,要查找当前目录中所有文件的行数,您可以这样做:
find . | xargs wc -l
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
我认为简单的解决方法是:
sh /dir/* > ./result.txt