在多个文件上运行shell脚本作为输入

mot*_*m79 2 bash shell

我有一个shell命令,格式如下:

my_cmd -I file1.inp -O file1.out
Run Code Online (Sandbox Code Playgroud)

进行某些处理file1.inp并将结果存储在其中的地方file1.out

在我的主目录中,我有许多格式为的文件:*.inp我想为所有这些文件运行此命令并将结果存储到*.out.我可以只用shell脚本来实现吗?

hek*_*mgl 5

你可以使用一个简单的循环:

for file in *.inp ; do
    my_cmd -I "${file}" -O "${file%%.inp}.out"
done
Run Code Online (Sandbox Code Playgroud)

${file%%.inp}是一个所谓的参数扩展.它将有效地.inp从输入文件名中删除扩展名.


一件事(感谢Jean-FrançoisFabre).如果文件夹不包含任何.inp文件,则上述循环将以$file具有文字值的方式运行一次*.inp.为避免这种情况,您需要设置nullglob选项:

shopt -s nullglob # set the nullglob option
for file in *.inp ; do
    my_cmd -I "${file}" -O "${file%%.inp}.out"
done
shopt -u nullglob # unset the nullglob option
Run Code Online (Sandbox Code Playgroud)

  • @ motam79你可以使用`&`符号来分叉你的指令.在你的for循环中,你可以写`my_cmd -I"$ {file}" - O"$ {file %%.inp} .out"&` (2认同)