Home > Software engineering >  Exclude directory in a windows command line recursive search
Exclude directory in a windows command line recursive search

Time:12-10

After researching how to move files w certain words in their title recursively...and assuming this is the result ( I have the code in a win11 .bat file which sits in the root of d:\ )

for /r %%a IN (*apples* *oranges*) do (
move /y "%%a" "d:\fruit" )

Is there a way I can EXCLUDE a specific directory from the search? The directory "d:\bananas" for example?

Thanks!

CodePudding user response:

Try

for /r %%a IN (*apples* *oranges*) do (
echo "%%a"|find /i "d:\bananas\" >nul
if errorlevel 1 move /y "%%a" "d:\fruit" )

The find sets errorlevel to 1 if the string is not found.

CodePudding user response:

This run faster because it does not execute the 17 Kb find.exe command on each file:

setlocal EnableDelayedExpansion

set "exclude=d:\bananas"
for /r %%a IN (*apples* *oranges*) do (
   if "!exclude:%%~DPa=!" equ "%exclude%" move /y "%%a" "d:\fruit"
)

The "!exclude:d:\bananas\=!" part try to delete the path of each file from the variable. If the result is the same, the path is not in the variable...

You can also do a partial search of the beginning of the path of each file this way:

for /r %%a IN (*apples* *oranges*) do (
   set "filepath=%%~DPa"
   if "!filepath:d:\bananas=!" equ "!filepath!" move /y "%%a" "d:\fruit"
)
  • Related