[英]Remove trailing backslash from a path with batch
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?如何从文件名或最后一个字符中删除最后一个
\
?
You can use substring expansion:您可以使用 substring 扩展:
set "var=C:\Directory\Directory2\"
echo %var:~0,1%
obviously there might be a case where the last character is not \
.显然,可能存在最后一个字符不是
\
的情况。 Therefore we rather test if it is the case, only then do we exclude it.因此,我们宁愿测试是否是这种情况,然后才将其排除。
if "%var:~-1%" == "\" set "var=%var:~0,-1%"
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.想想
C:\
- 指向驱动器的根目录,而C:
指向它的当前目录。
The most reliable way of dealing with potential trailing backslashes is probably to append .
处理潜在尾部反斜杠的最可靠方法可能是 append
.
, because C:\Directory\Directory2\
is equivalent to C:\Directory\Directory2\.
, 因为
C:\Directory\Directory2\
等价于C:\Directory\Directory2\.
, C:\Directory\Directory2
and C:\Directory\Directory2.
,
C:\Directory\Directory2
和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 .
如果后缀因美观原因而受到干扰,请在附加后通过
for
循环解决它.
: :
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. 修饰符
~f
定义解析路径并将相对路径转换为完整/绝对路径。
If the provided path may even end with \.
如果提供的路径甚至可能以
\.
or is something like C:.
或者类似于
C:.
, appending another .
, 附加另一个
.
would change its target;会改变目标; this however can be solved by another
for
loop before appending .
然而,这可以在附加之前通过另一个
for
循环来解决.
: :
set "dirPath=C:\Directory\Directory2\."
for %%J in ("%dirPath%") do for %%I in ("%%~fJ.") do echo "%%~fI"
Note that for
resolves wildcards like ?
请注意,
for
解析通配符,例如?
and *
.和
*
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.