有人能提供代码来做以下工作吗: 假设有一个文件目录,所有这些文件都需要通过一个程序运行。程序将结果输出到标准输出。我需要一个脚本,它将进入一个目录,对每个文件执行命令,并将输出连接到一个大输出文件。
例如,在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
其他回答
我需要将所有.md文件从一个目录复制到另一个目录,下面是我所做的。
I在**/*.md;执行mkdir -p ../docs/"$i" && rm -r ../docs/"$i" && cp "$i" "../docs/$i" && echo "$i -> ../docs/$i";完成
这很难读,所以让我们分解一下。
第一张CD放入你的文件目录,
对于I在**/*.md;对于模式中的每个文件
Mkdir -p ../docs/"$i"把这个目录放在包含你的文件的文件夹外的docs文件夹中。这将创建一个与该文件同名的额外文件夹。
Rm -r ../docs/"$i"删除mkdir -p创建的额外文件夹
Cp "$i" "..复制实际文件
Echo“$i -> ..”/docs/$i" Echo你所做的
; 从此过上幸福的生活
下面的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的输出。
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