首页 > 解决方案 > 批处理脚本 - 在目录中的每个文件上运行程序

问题描述

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

在每个目录(具有特定名称)中有 2 个文件,每个目录具有相同的名称: dft_opt.inpdft_nmr.inp,它们必须按此顺序使用,因为第二个需要来自第一个输出的数据。在命令行中,

orca dft_opt.inp > dft_opt.log

由于需要精确的顺序,该程序的工作方式就像我正在为批处理脚本而苦苦挣扎。这是我最好的尝试。

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



标签: batch-filecmdforeach

解决方案


@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检查是否existdft_opt.inp如果确实存在,请检查和的文件是否都dft_nmr.inp存在。如果确实存在,则将目录更改为文件的目录并orca在这些文件上运行程序并将输出重定向到日志文件。


推荐阅读