I have such a filename saved in a variable:
C:\Directory\Directory2\
And now I want to have this:
C:\Directory\Directory2
How to cut the last \
from the filename or the last character?
Well, just don't! Removing the trailing backslash may change the target the path points to; think of C:\
– which points to the root directory of the drive, while C:
points to the current directory of it.
The most reliable way of dealing with potential trailing backslashes is probably to append .
, because C:\Directory\Directory2\
is equivalent to C:\Directory\Directory2\.
, C:\Directory\Directory2
and C:\Directory\Directory2.
, because all these paths point to exactly the same location.
If the suffix disturbs for cosmetic reasons, resolve it by a for
loop after having appended .
:
set "dirPath=C:\Directory\Directory2\"
for %%I in ("%dirPath%.") do echo "%%~fI"
The modifier ~f
defines to resolve the path and also converts relative ones to full/absolute ones.
If the provided path may even end with \.
or is something like C:.
, appending another .
would change its target; this however can be solved by another for
loop before appending .
:
set "dirPath=C:\Directory\Directory2\."
for %%J in ("%dirPath%") do for %%I in ("%%~fJ.") do echo "%%~fI"
Note that for
resolves wildcards like ?
and *
.