How does “FOR” work in cmd batch file?

前端 未结 12 1073
面向向阳花
面向向阳花 2020-12-03 10:40

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

12条回答
  •  没有蜡笔的小新
    2020-12-03 11:19

    You've got the right idea, but for /f is designed to work on multi-line files or commands, not individual strings.

    In its simplest form, for is like Perl's for, or every other language's foreach. You pass it a list of tokens, and it iterates over them, calling the same command each time.

    for %a in (hello world) do @echo %a
    

    The extensions merely provide automatic ways of building the list of tokens. The reason your current code is coming up with nothing is that ';' is the default end of line (comment) symbol. But even if you change that, you'd have to use %%g, %%h, %%i, ... to access the individual tokens, which will severely limit your batch file.

    The closest you can get to what you ask for is:

    set TabbedPath=%PATH:;= %
    for %%g in (%TabbedPath%) do echo %%g
    

    But that will fail for quoted paths that contain semicolons.

    In my experience, for /l and for /r are good for extending existing commands, but otherwise for is extremely limited. You can make it slightly more powerful (and confusing) with delayed variable expansion (cmd /v:on), but it's really only good for lists of filenames.

    I'd suggest using WSH or PowerShell if you need to perform string manipulation. If you're trying to write whereis for Windows, try where /?.

提交回复
热议问题