1.

Solve : Expanding and looping over paths?

Answer»

Hi. I'd like to make a batch file that loops over a semicolon separated path variable and displays each directory on a different line. I am having 2 problems trying to do this:

1. I am passing in the name of the path variable to loop over ("path", "classpath", etc). How can I expand that path in a variable. For example, in my batch file, %1 = "path". How can I assign the contents of %path% to a variable. I don't want to test if "%1" = "path" as I want this to be flexible enough to handle any path variable (I have a lot of them).

2. How can I loop over a semicolon separated string and display each path on a separate line. I've been playing with "for /f" quite a bit, but haven't figured out how to manipulate the tokens and delimiters keywords.

Thanks!You MEAN something like this?

for /f "delims=;" %%a in ('echo %path%') do echo %%a >> pathlist.txtSort of. When I substituted this into my macro, I got a file where all the paths were on a SINGLE line and separated by a SPACE:

c:\dir1 c:\dir2 c:\dir3...

What I want is a listing on my console where each path is on a separate line:
c:\dir1
c:\dir2
...

Also, if %1=PATH, what would the echo look like? How would I GET the contents of the path variable. For example:

displaypath path
c:\dir1
c:\dir2
...

This would set %1="path" in "displaypath". How do I get to the contents of path?
Thanks!Your problem is that the /F switch tells FOR to treat whatever is in the parentheses as a SEQUENCE of lines, and the PATH environment variable string is just one line. What you can do is replace every semicolon with the sequence quote-space-quote so that FOR can chop up the line. Then you can use the ~ variable modifier to dequote the substring. Or not as the case may be.

This code parses a semicolon delimited string into separate lines. The IF test is to filter out the results of multiple or trailing semicolons. For want of any better idea, I called it semi-parse.bat. The parameter passed is quoted to avoid problems with spaces.

Code: [Select]@echo off
set string=%~1
for %%A in ("%string:;=" "%") do (
if not "%%~A"=="" echo.%%~A
)
Code: [Select]C:\>semi-parse.bat "apples;pears;oranges"
apples
pears
oranges

C:\>set teststring=shoes;gloves;hat and coat

C:\>semi-parse.bat "%teststring%"
shoes
gloves
hat and coat

C:\>set teststring=mother;;father;sister;brother;

C:\>semi-parse.bat "%teststring%"
mother
father
sister
brother

C:\>semi-parse.bat "%path%"
C:\WINDOWS\system32
C:\WINDOWS
C:\WINDOWS\System32\Wbem

C:\>Thank you both. This is very helpful! It basically solves my problem and with a little tuning will be exactly what I wanted.



Discussion

No Comment Found