Mostly Linux & Python syntax notes and hyperlinks.

Wednesday, January 22, 2025

Windows Batch Script - parse out Drive and top-level directories

Given 

echo %CD%

   result:   E:\abcd\efg\hijk\lmno

To pull out "E:\abcd\efg" from this path and set it to a variable named TRUNK:

for /f "tokens=1,2,3 delims=\" %%G in ("%CD%") do set TRUNK=%%G\%%H\%%I

echo %TRUNK%

   result:    E:\abcd\efg

Note the need to restore the backslashes that were pulled out as token delimiters.

If you prefer to convert the path to use forward slashes while you're at it:

for /f "tokens=1,2,3 delims=\" %%G in ("%CD%") do set TRUNK=%%G/%%H/%%I

echo %TRUNK%

   result:   E:/abcd/efg