SSS
SSS

Reputation: 2452

wild card in if statement in batch file

I am using a windows bactchfile to grab all folders that don't start with "abc". Therefore, ignoring folders names abcd, and abc123, etc. It seems the IF statement does not process wild cards. How can I go about doing this.

for /D %%A in (*) do ( 
    if not %%A == abc* (Do commands)
)

I found some help saying to use something like the following but am unable to get the correct syntax.

%variable:~offset,length%

I tried this syntax but its not correct:

if not %%A:~0:3 == abc (Do commands)

Upvotes: 0

Views: 247

Answers (2)

dbenham
dbenham

Reputation: 130839

for /f "eol=: delims=" %%F in ('dir /b * ^| findstr /vbi abc') do (
  REM your commands processing file %%F here
)

The eol=: is probably not necessary. I include it because you do not want to exclude any files that begin with the EOL character, which defaults to ;, and it is possible for a file name to begin with ;. No file can begin with :, so that is safe for EOL.

I opted to use FOR /F because that caches the entire list of files before the loop executes any command, leaving you free to do anything to those files, including renaming them.

If you use a simple FOR loop, then it is possible that a renamed file would get processed twice (or more!) because FOR can begin processing files before it has finished discovering them. The new name of a renamed file could show up later in the list and get reprocessed.

Upvotes: 0

Stephan
Stephan

Reputation: 56180

just to give an alternative without using a temporary variable (and therefore no need for delayed expansion):

for %%a in (*) do (
   echo %%a|findstr /ib "abc" || (
     echo Do commands with '%%a'
   )
)

findstr /ib looks for strings that start (b) with a certain substring (abc), ignoring capitalization (i)
|| works as "if previous command (findstr) failed then"

Upvotes: 2

Related Questions