绝对路径:分隔路径并保存在字符串中



使用批处理命令如何从字符串中获取文件夹路径/目录?

例如,如果我有字符串"C:\user\blah\abc.txt",我如何拆分字符串以便我可以只获取文件夹部分,即"C:\user\blah\"?

如果在批处理文件的命令行中传递字符串"C:\user\blah\abc.txt",如何将该字符串拆分为文件夹部分?

REM // Grab "C:userblahabc.txt" from the command line
SET path="%*" 
REM // The following doesn't successfully capture the "C:userblah" part
SET justFolder=%path:~dp1%
~

dp 选项仅适用于批处理参数 (%1 %2 ...) 或 FOR 替换参数 (%%a %%b ...)。阅读HELP CALL .

因此,要实现您想要的,请尝试以下代码

call :setJustFolder "%*"
echo %justFolder%
goto :eof
:setJustFolder
set justFolder=%~dp1
goto :eof

作为旁注,我个人的偏好是不在用户输入的文件名周围添加" 。我会简单地将以前的代码编码为

set justFolder=%~dp1
echo %justFolder%
如果要

从字符串或当前工作目录中获取路径,则几乎相同。

set "myPath=%~dp1"
echo %myPath%

或者,如果您想从变量中获取它,您可以使用 FOR/F .

set myPath=C:windowsxyz.txt
for /F "delims=" %%A in ("%myPath%") do echo %%~dpA

相关内容

最新更新