Search code examples
windowsbatch-filefor-loopcommand-lineimagemagick-convert

Nested loop with different Magick command in bat Windows


I am trying to convert many pdf files into jpg but only if it has 1 page. I rather work with multi-pages pdf than images. I tried different command and get them working correctly individually, both identify and convert. However, I couldn't combine them to work in a folder. I haven't got to the point of conditional operation (if less than 2 pages, convert it). I am using this code

pause
set path="C:\Program Files\ImageMagick-7.0.8-Q16\";%path%
FOR /r %%g in (*.pdf) DO (
    for /f %%i in ('identify -format %n %%g') do set pgs=%%i
    echo %pgs%
echo "%%g"
::convert %%~ng%%~xg %%~ng.jpg
::del %%~ng.pdf
)
pause

It says the syntax of the command is incorrect. The commented out part is working correctly. I don't know command line very well so any help is greatly appreciated.


Solution

  • This is the final code that works. It does a lot of little things

    • Loops through folders and subfolders
    • Evaluate every pdf file
    • If the pdf file does NOT have "c" in its name AND have more than 1 page, rename at "c" after its name before the extension. (This help avoid process processed files)

    SETLOCAL EnableDelayedExpansion

    pause 
    set path="C:\Program Files\ImageMagick-7.0.8-Q16\";%path%
    
    FOR /d /R %%i in (*) DO ( 
    
        cd "%%i"
            FOR /r %%g in (*.pdf) DO (
            (Echo "%%g" | FIND /I "_c_" 1>NUL )||(
                for /f %%i in ('magick identify -format %%n "%%g"') do if %%i gtr 1 ren %%~ng%%~xg %%~ng_c_%%~xg
    )
    )
    cd..
    )
    pause