First of all, don’t use
path as a variable name.
Windows Command Prompt
(unlike most components of Unix, including the shells)
treats variable names in a case-insensitive way,
path is the same as
PATH, which is your execution search path,
and if you assign something random to that, you’ll be in a world of hurt.
(I presume that you know that
set /? documents these forms.)
This one is substitution:
C:\> set play=food
C:\> echo %play:foo=bar%
C:\> set animal=cat
C:\> echo %animal:at=ow%
This supports a very limited pattern-matching capability;
%variable:*str1=str2% will find and delete
everything up to and including the first occurrence of
and replace it with
%variable:*\=% will replace
everything up to and including the first
\ with null.
C:\Windows\Example\001 Example\005 Example,
%pathname:*\=% will evaluate to
Windows\Example\001 Example\005 Example (without the
If your pathname will always have four levels, you can do
for %%I in (%pathname%) do set tempname=%%~I
for statement is a bit of a kludge.
It’s a loop that is guaranteed to execute exactly once
with index variable
%%I set to the value of
Then it assigns
%%~I is the value of
%%I (i.e., the value of
except, if that string begins and ends with quote (
they are removed.
If you’re sure that
%pathname% doesn’t begin and end with quotes
(e.g., because you’ve already done this, or something equivalent),
you can skip this step and just start by saying
If the pathname has an indeterminate number of levels, do
for %%I in (%pathname%) do set tempname1=%%~I
if not %tempname1% == %tempname2% ( set tempname1=%tempname2% & goto loop )
which loops until there are no
Actually, its behavior may be more complex if
%pathname% is null (empty),
or if it contains wildcard (pattern-matching) characters like
There may be other peculiar cases that I haven’t found.
(Please let me know if there’s a cleaner way to deal with quotes.)
Warning: I’ve observed
to behave oddly if
%variable% is null.