如何“FOR”在cmd批处理文件中工作?
我已经编程了几十种语言20年,但我永远不能理解为什么FOR工作在windows cmd shell批处理文件,无论我多么努力。我阅读
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.ss64.com/nt/for .html
和其他几个在互联网上的文章,但仍然混淆,不能完成任何事情。
and several other articles on the internet but still confuse and cannot accomplish anything.
对于一个更具体的问题,我如何遍历每个路径在%PATH%变量?
我尝试过
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 ?
没有答案真的有效。我设法自己找到解决方案。
这有点麻烦,但它解决了我的问题:
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
)
)
$ b b
哦!我讨厌批量文件编程!!
Oh ! I hate batch file programming !!
更新
Mark的解决方案更简单,它不会与包含空格的路径一起工作。这是Mark的解决方案的一个小修改版本
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:#= !
)