I've been programming in dozens of languages for 20 years but I could never understand how "FOR" work in windows cmd shell batch file, no matter how hard I tried. I read
http://www.amazon.com/Windows-Administration-Command-Line-Vista/dp/0470046163/ref=sr_1_1?ie=UTF8&s=books&qid=1241362727&sr=8-1
http://www.ss64.com/nt/for.html
and several other articles on the internet but still confuse and cannot accomplish anything.
Can anybody give me a concise explaination on how "FOR" works in general ?
For a little more specific question, how can I iterate through each path in %PATH% variable ? I've tried with
rem showpathenv.bat for /f "delims=;" %%g in ("%PATH%") do echo %%g
That'd show only the first path, not all of them. Why ? What I do wrong ?
FOR /D - Loop through several folders. FOR /L - Loop through a range of numbers. FOR /F - Loop through items in a text file. FOR /F - Loop through the output of a command.
There is no meaning of :2 , as the whole construct is meaningless. (yes, it executes, but it just sets a variable (name given by the first parameter to the batch file) to nothing.
&& runs the second command on the line when the first command comes back successfully (i.e. errorlevel == 0 ). The opposite of && is || , which runs the second command when the first command is unsuccessful (i.e. errorlevel != 0 ).
In this case, we used the * wildcard to mean "all files in the current directory". This command prints the line containing the given string, and if there's more than one file in the list, the name of the file where it was found.
None of the answers actually work. I've managed to find the solution myself. This is a bit hackish, but it solve the problem for me:
echo off setlocal enableextensions setlocal enabledelayedexpansion set MAX_TRIES=100 set P=%PATH% for /L %%a in (1, 1, %MAX_TRIES%) do ( for /F "delims=;" %%g in ("!P!") do ( echo %%g set P=!P:%%g;=! if "!P!" == "%%g" goto :eof ) )
Oh ! I hate batch file programming !!
Updated
Mark's solution is simpler but it won't work with path containing whitespace. This is a little-modified version of Mark's solution
echo off setlocal enabledelayedexpansion set NonBlankPath=%PATH: =#% set TabbedPath=%NonBlankPath:;= % for %%g in (%TabbedPath%) do ( set GG=%%g echo !GG:#= ! )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With