aurelSon
aurelSon

Reputation: 73

In batch, how to check if dir names contains a substring while looping?

I would like to loop from current directory to the subdirectories and display only directories that does not contain a specific string (folder1 in this example):

@setlocal enableextensions enabledelayedexpansion
@echo off

for /f "tokens=*" %%G in ('dir /b /s /a:d %cd%') do ^
set str1=%%G
if not x%str1:folder1=%==x%str1% echo %%G

endlocal

But, this script display nothing, yet I do have several subdirectories to go through.

Thank you for your help

Aurel

Upvotes: 0

Views: 3470

Answers (1)

Aacini
Aacini

Reputation: 67216

You almost done it:

@echo off
setlocal EnableExtensions EnableDelayedExpansion

for /f "tokens=*" %%G in ('dir /b /s /a:d') do (
   set "str1=%%G"
   if not "!str1:folder1=!" == "!str1!" echo %%G
)

endlocal
  • If you want the dir command show folders in current directory, just use dir /B /S /A:D; it is not necessary to include the %cd% part (in the same way that you type dir at the command-prompt, but not dir %cd%.
  • In set command it is convenient to enclose the variable and its value in quotes: set "str1=%%G"; this avoids problems caused by any non-visible space. The same apply for the values in if command.
  • When a variable is modified inside a for or if commands, the new value must be expanded via ! (that is the purpose of EnableDelayedExpansion).
  • The value of %%G replaceable parameter is valid only inside the for. Use parentheses to enclose all the commands that goes inside the for.

Upvotes: 2

Related Questions