批处理脚本-在目录中的每个文件上运行程序

时间:2020-05-12 19:55:14

标签: batch-file cmd foreach

我需要运行一个程序,该程序在大量文件上使用.inp文件并提供.log文件。

每个目录(具有特定名称)中有2个文件,每个目录具有相同的名称: dft_opt.inp dft_nmr.inp ,并且必须按此顺序使用它们,因为第二个需要第一个输出中的数据。 在命令行中,程序的工作方式类似于

orca dft_opt.inp > dft_opt.log

由于所需的精确顺序,我在批处理脚本中苦苦挣扎。 这是我最好的尝试。

for %%d in (*/orca_input); 
do (cd "%%d" & runningprogram); 
done



1 个答案:

答案 0 :(得分:0)

@echo off
setlocal

rem Iterate each folder in the current directory.
for /d %%A in (*) do (

    rem Check if orca_input subfolder exist.
    if exist "%%~A\orca_input\" (

        rem Check if dft_opt.inp and dft_nmr.inp files exist.
        if exist "%%~A\orca_input\dft_opt.inp" if exist "%%~A\orca_input\dft_nmr.inp" (

            rem Change working directory to where the files are temporarily.
            pushd "%%~A\orca_input" && (

                rem Run the program.
                orca dft_opt.inp > dft_opt.log
                orca dft_nmr.inp > dft_nmr.log
                popd
            )
        )
    )
)

此代码适用于命令tree /a /f的示例结构:

+---a
|   \---orca_input
|           dft_nmr.inp
|           dft_opt.inp
|
\---b
    \---orca_input
            dft_nmr.inp
            dft_opt.inp

文件夹ab由第一个for循环迭代。检查orca_input是否为exist。如果确实存在,请检查dft_opt.inpdft_nmr.inp的两个文件是否都存在。如果确实存在,则将目录更改为文件目录,并对这些文件运行程序orca,然后将输出重定向到日志文件。