Search code examples
batch-filewebp

Windows batch : find string contains another string inside a for loop


I am trying to convert a set of PNG images to WEBP images using cwebp encoder. I managed to do it using a JAVA program but now I want to write a batch file to do this task. I already got metal03326's solution after some searching. But I want one modification in this that 9 patch images should be skipped.

Here is what I did :

pushd %1

set "DOTNINE=.9"

echo %DOTNINE%

for /f "delims=" %%n in ('dir /b /s /a-d-h-s') do (

set MY=%%~nn

set MY=%MY:~-2%

rem IF NOT ".webp" == "%%~xn" IF NOT "MY" == ".9" ("%~dp0cwebp.exe" -q 80 "%%n" -o "%%n.webp") ELSE (echo File already WEBP.)

)

popd

But I'm getting a syntax error. What is wrong in the above code?


Solution

  • To re-assign a variable (namely MY) multiple times in a loop you have to use delayed expansion:

    setlocal enableDelayedExpansion
    pushd "%~1"
    for /f "delims=" %%n in ('dir /b /a-d-h-s') do (
        set MY=%%~nn
        set MY=!MY:~-2!
        IF NOT ".webp" == "%%~xn" IF NOT "!MY!" == ".9" ("%~dp0cwebp.exe" -q 80 "%%n" -o "%%n.webp") ELSE (echo File already WEBP.)
    )
    popd