Clothahump Clothahump - 3 months ago 11
Bash Question

Traverse path variable with FOR in Windows

My faithful path traversal method no longer works - it sees spaces as delimiters. It's been a while since I needed to do batch programming.

When using the

FOR
loop, the only one that allows delimiters are the
FOR /F
option.

I don't want to create a temporary file containing the path, was hoping to do something like below:


C:\Users>for /f "delims=;" %i in %path% do echo %i
C:\Program was unexpected at this time.

C:\Users>for /f "delims=;" %i in (%path%) do echo %i
\Common was unexpected at this time.

C:\Users>for /f "delims=;" %i in 'foo;bar' do echo %i
'foo was unexpected at this time.



Thanks - the
FOR %I in ("%PATH:;=";"%") do @echo %~I
is working perfect.
Did not realize the FOR command is so powerful.

Answer

Use a standard for loop rather than for /F "delims=;" with some smart sub-string replacement:

for %I in ("%PATH:;=";"%") do @echo %~I

Supposing PATH contains C:\Program Files\someapp1\app1.exe;C:\Program Files\someapp2\app2.exe;C:\Program Files\someapp3\app3.exe, you will receive the following output:

C:\Program Files\someapp1\app1.exe
C:\Program Files\someapp2\app2.exe
C:\Program Files\someapp3\app3.exe

This works only in case none of the paths are surrounded by " and none of them contains ;.

Comments