本文介绍了“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.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 ?

推荐答案

没有一个答案实际有效.我已经设法自己找到了解决方案.这有点hackish,但它为我解决了问题:

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

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

08-11 22:26