Thierry Savard Saucier
Thierry Savard Saucier

Reputation: 449

Batch file : how to get a specific part of a folder path

I'm currently looping threw the subfolders of a known directly. I would like to grab the folder that contains the file I'm looking for, but only that folder's name, not the whole path, and preferably in a different variable to be use later on in the batch file ...

pause
CD c:\%username%\testFolder\Program\OLD\

For /R %%G in (test.t?t) do Echo %%G

pause

Now, this shows me the file I'm looking for : C:\User\testFolder\Program\OLD\myfile\exemple1\test.txt

what I would like is to replace the Echo %%G to set in a variable the "unknown" folders and subfolder, something along the line of

For /R %%G in (test.t?t) do set var1 = myfile\exemple1

anyone can point to what I'm missing ?

Upvotes: 1

Views: 1604

Answers (1)

rojo
rojo

Reputation: 24476

If you for /? in a cmd console, you'll see runtime variables on the last couple of pages. Using %%~dpG notation you can get the full drive\path specification of matched files. Then, using substring substitution and delayed expansion, replace %CD% with nothing. Finally, you can strip the leading and trailing backslash with a numeric substring -- !varname:~1,-1!.

@echo off
setlocal enabledelayedexpansion

cd /d "c:\%username%\testFolder\Program\OLD\"

for /R %%G in (test.t?t) do (
    set "var1=%%~dpG"
    set "var1=!var1:%CD%=!"
    if "!var1!"=="\" (echo .\) else echo(!var1:~1,-1!
)

If you wish, you can prevent echoing duplicates by echoing only if the previous match does not equal the current one.

@echo off
setlocal enabledelayedexpansion

cd /d "c:\%username%\testFolder\Program\OLD\"

for /R %%G in (test.t?t) do (
    set "var1=%%~dpG"
    set "var1=!var1:%CD%=!"
    if not "!var1!"=="!prev!" (
        if "!var1!"=="\" (echo .\) else echo(!var1:~1,-1!
    )
    set "prev=!var1!"
)

Upvotes: 2

Related Questions