“为"如何?在cmd批处理文件中工作? [英] How does "FOR" work in cmd batch file?

查看:35
本文介绍了“为"如何?在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.amazon.com/Windows-管理-命令行-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.

谁能简要解释一下FOR"的一般工作原理吗?

Can anybody give me a concise explaination on how "FOR" works in general ?

对于一个更具体的问题,我如何遍历 %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
  )
)

哦!我讨厌批处理文件编程!!

Oh ! I hate batch file programming !!

更新

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:#= !
)

这篇关于“为"如何?在cmd批处理文件中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆