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

Microsoft Windows
Post Reply
User avatar
Posts: 336
Joined: 2021-Jul-12, 1:37 pm

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

Post by MigrationUser »

20 Jan 2018 01:30

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 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


#2 20 Jan 2018 06:12
Shadow Thief

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

Code: Select all

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

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


#3 20 Jan 2018 14:51

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!
Post Reply