Captain Morgan
Captain Morgan

Reputation: 243

Perform Action on Files in Directory it They Don't begin with a Certain String

I'm trying to write a program that converts photos. It works fine in converting all photos, but considering how the outputs begin with asd, I'd like to have it skip over files that begin with it. Here's some example code to clarify (using echo as my process for simplicity sake):

for %%A in (%2) do (
set fname="%%A"
    if not "%fname:~0,3%"=="asd" (
        echo input "%%A" now produce "asd_%%A"
    )
)

Basically, to just mass convert I'd run it without the set and if parts. I'd run this like my_cmd --all *.png. Again, excluding those two parts has this running fine. Once I include them it acts (to me) unpredictably. If I can avoid setting the variable fname for this, that'd be awesome, but from what I read in other posts, I cannot. On this note, I should probably make these variables temporary/local/delete/etc. How would I do this? I'm pretty new to batch so I have no clue even when looking online.

Upvotes: 0

Views: 32

Answers (1)

Squashman
Squashman

Reputation: 14290

A couple of things wrong with your code.

Don't assign quotes to your variables unless you are certain you know what you are doing and why you need them. You can use quotes though to protect the assignment of the string to the variable.

You are inside a parenthesized code block which requires the use of delayed expansion for your variables. This has to be enabled with a setlocal command and you also need to reference your variables with exclamation points instead of percent symbols.

@echo off
setlocal enabledelayedexpansion
for %%A in (%2) do (
    set "fname=%%A"
    if not "!fname:~0,3!"=="asd" (
        echo input "%%A" now produce "asd_%%A"
    )
)

Alternatively you could use the DIR command to list your files and pipe it to the FINDSTR command to find files that do not begin with your string.

FOR /F "delims=" %%G IN ('dir /a-d /b *.png ^|findstr /I /B /V "asd"') do echo %%G

Upvotes: 1

Related Questions