Reputation: 13
I have found on a couple of web pages different ways of splitting the Windows %PATH variable onto several lines:
1. for /f "delims=;" %a in ("%path%") do echo %a . . . (doesn't work)
2. for %G in ("%Path:;=" "%") do @echo %G
3. for %a in ("%Path:;=";"%") do @echo %~a
4. ECHO.%PATH:;= & ECHO.%
Can anyone please explain why (1) doesn't work, and how (2), (3) and (4) do
?
And, is there a way to do it with bash-like variable semantics - i mean, with ENABLEDELAYEDEXPANSION ?
Upvotes: 1
Views: 256
Reputation: 70923
1 for /f
iterates over a set of lines. It can split the line into tokens, but not iterate over them
2 and 3 - Each semicolon in the variable is replaced with a quoted delimiter (in 2 it is a space and in 3 a new semicolon) and the variable enclosed in quotes, so at the end we have
path dir1;dir2;dir3
quoted "dir1;dir2;dir3"
replacement
case 2 - "dir1" "dir2" "dir3"
case 3 - "dir1";"dir2";"dir3"
^ See here the replacement
Then a for
command is used to iterate over a delimited (by spaces or semicolons) list of quoted elements
4 Here the parser is used. Lines are parsed and then executed. At parse time each semicolon in the path
variable is replaced with & echo.
, that is, a command concatenation and a new echo
command. So the efect is that when the line is readed it is processed as
Read line
echo %path:;= &echo.%
v..............v Variable expanded
dir1;dir2;dir3 = dir1 & echo.dir2 & echo.dir3
Final command after parser work
echo dir1 &echo.dir2 &echo.dir3
^ .........^... echo commands included in line at parse time
With delayed expansion active,
1 will also not work, it has the same problem.
2 and 3 should work the same. The only "problem" is that setlocal enabledelayedexpansion
has no effect on a command line (what you are using in the question). You will need to use a batch file or start a separate cmd
instance with delayed expansion active
cmd /v /c"for %a in ("!path:;=";"!") do @echo %~a"
The only difference is that from a batch file (not from command line), existing exclamations inside the variable will be lost when the @echo %%~a
is parsed.
4 will not work. It uses the fact that the parser does normal variable expansion before the command line is processed for command handling. That way when the command is analyzed the full chain of echo
commands can be found.
But with delayed expansion syntax, the expansion is done after the command has been parsed and what will be echoed to console is the chain of echo
commands, not the execution of them.
Upvotes: 1