#1 20 Jan 2018 01:30

ronczap
Member
Registered: 20 Jan 2018
Posts: 2

Please explain this: for %%a in ("%path:;=" "%") do @echo %%~a

I know this works great to parse the PATH environment variable and shows each path on a separate line but I don't understand the syntax or how it works.
It obviously is parsing the path variable using the semicolon to split the string.
I can't find any info on Microsoft Technet or anywhere else which explains the syntax.

Thanks for any help!

from the ss64.com CMD Path page:

To view each item on a single line use this:
for %G in ("%path:;=" "%") do @echo %G

Or in a batch file:
for %%G in ("%path:;=" "%") do @echo %%G

Offline

#2 20 Jan 2018 06:12

Shadow Thief
Member
Registered: 12 Jul 2012
Posts: 171

Re: Please explain this: for %%a in ("%path:;=" "%") do @echo %%~a

It's actually not using the semicolon to split the string (well, it sort of is - you'll see in a second).

The %PATH% variable consists of a bunch of different folders joined with semicolons. It looks something like
C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem

The %path:;=" "% is string substitution, where each semicolon is replaced with " ". String substitution uses the format %variable_name:string_to_be_replaced=new_string%. This results in the %PATH% variable now having the value
C:\Program Files (x86)\Intel\iCLS Client\" "C:\Program Files\Intel\iCLS Client\" "C:\Windows" "C:\Windows\System32\WindowsPowerShell\v1.0\" "C:\WINDOWS\system32" "C:\WINDOWS" "C:\WINDOWS\System32\Wbem. The quotes on either side of %path:;=" "% are actually appended to either side of the value.

A regular for loop with no options iterates over a set of items. In this case, that set of items is a group of space-separated quoted paths, making the code translate to

for %%G in ("C:\Program Files (x86)\Intel\iCLS Client\" "C:\Program Files\Intel\iCLS Client\" "C:\Windows" "C:\Windows\System32\WindowsPowerShell\v1.0\" "C:\WINDOWS\system32" "C:\WINDOWS" "C:\WINDOWS\System32\Wbem") do echo %%~G

The ~ removes the surrounding quotes so you're left with just the individual paths.

For more info, read https://ss64.com/nt/syntax-replace.html

Last edited by Shadow Thief (20 Jan 2018 06:14)

Offline

#3 20 Jan 2018 14:51

ronczap
Member
Registered: 20 Jan 2018
Posts: 2

Re: Please explain this: for %%a in ("%path:;=" "%") do @echo %%~a

Shadow Thief,

Thanks for the quick reply and excellent explanation!  I've never come across the "Variable Edit/Replace" string substitution feature before.

I tend to use Vbscript for most things but I came across this batch/command level code and could not determine what it was doing.

I appreciate your help!

Offline

Board footer

Powered by FluxBB