Search code examples
cmdforeachfindstr

Why does FINDSTR match and output nothing on being executed on several folders with a FOR loop?


I'm writing a batch script to iterate a findstr over files in different directories, but I get nothing. I'm sure that the string exists in all the files.

This is my script:

setlocal

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

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

        rem Check if dft_opt.log files exist.
        if exist "\orca_input\%%~A\dft_opt.log" (

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

                rem Run the program.
                findstr /C:"Last Energy change" dft_opt.log > energychange.dat
                popd
            )
        )
    )
)

I'm not able to see errors.

Edit:

I tried this script according to the advice, but no file .dat is created.

setlocal

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

    rem Check if dft_opt.log files exist.
    if exist "\orca_input\%%~A\dft_opt.log" (         

        rem Run the program.
        findstr /C:"Last Energy change" "\orca_input\%%~A\dft_opt.log" >"\orca_input\%%~A\energychange.dat"
    )
)

Solution

  • Let's try this:

    setlocal
    
    rem Iterate each folder in the current directory.
    for /d %%A in (*) do (
       rem Check if dft_opt.log file exists.
       if exist "orca_input\%%~A\dft_opt.log" (
          findstr /C:"Last Energy change" "orca_input\%%~A\dft_opt.log">"orca_input\%%~A\energychange.dat"
       )
    )
    

    I feel like we need to get the folder structure figure out.

    Another alternative:

    setlocal
    
    rem Iterate each folder in the current directory.
    for /d %%A in (*) do (
       rem Check if dft_opt.log file exists.
       if exist "%%~A\orca_input\dft_opt.log" (
          findstr /C:"Last Energy change" "%%~A\orca_input\dft_opt.log">"%%~A\orca_input\energychange.dat"
       )
    )
    

    3rd try:

    setlocal
    
    rem Iterate each folder in the current directory.
    for /d %%A in (*) do (
       rem Check if dft_opt.log file exists.
       if exist "%%~A\dft_opt.log" (
          findstr /C:"Last Energy change" "%%~A\dft_opt.log">"%%~A\energychange.dat"
       )
    )