如何在批处理脚本中连接两个文件路径而不导致尾随“\”歧义?

问题描述 投票:0回答:3

对于下面的代码,我从 props 文件中获取 LIBDIR。

set strDestPath=%LIBDIR%"\Libraries\python\win\"
set strPythonZipSourcePath=%CTEDIR%"\Libraries\python\win\Python27.zip"

Call :UnZipFile %strDestPath% %strPythonZipSourcePath%

如果 props 文件的 LIBDIR 为“D:\WinLibraryes\”,那么我最终得到的 strDestPath

D:\WinLibraryes\\Libraries\python\win\
/*With double slash in the path*/

然后 UnZipFile 尝试访问该位置失败。

props 文件可能有 LIBDIR,带或不带尾随“\”。

如何连接这些路径以获得如下所示的正确路径?

D:\WinLibraryes\Libraries\python\win\
windows batch-file path concatenation
3个回答
0
投票

我想你可以

Set
新变量,同时检查 props 文件中的变量是否存在。 (毕竟,如果它们不存在,脚本也可能不会运行)

SetLocal EnableExtensions
PushD "%CD%"
CD /D "%LIBDIR%" 2>Nul || Exit /B
If Not Exist "%CD%\Libraries\python\win\" Exit /B
Set "strDestPath=%CD%\Libraries\python\win"
CD /D "%CTEDIR%" 2>Nul || Exit /B
If Not Exist "%CD%\Libraries\python\win\Python27.zip" Exit /B
Set "strPythonZipSourcePath=%CD%\Libraries\python\win\Python27.zip"
PopD

Call :UnZipFile "%strDestPath%" "%strPythonZipSourcePath%"

0
投票

我将模仿您的LIBDIR作为TMPLIBDIR来演示。 我们测试

TMPLIBDIR
的最后一个字符,看看它是否是
\
。我们不是从 TMPLIBDIR 中删除任何内容,而是决定之后是否将第一个
\
放在那里。要查看不同的结果,请在脚本中的
\
之后添加
Path

@echo off
setlocal enabledelayedexpansion
set "TMPLIBDIR=D:\WinLibraryes"
    if not "!TMPLIBDIR:~-1!"=="\" (
        set "strDestPath=%TMPLIBDIR%\Libraries\python\win\"
        ) else (
        set "strDestPath=%TMPLIBDIR%Libraries\python\win\"
 )

第一个条件在 TMPLIBDIR 之后添加

\
,而其他条件则不添加。


0
投票

我使用一个方便的子例程来构建路径:

@setlocal ENABLEEXTENSIONS
@set prompt=$G

set _var1=\Dir1\\\\Dir2\
set _var2=\Dir3\Dir4
set _var3=Relative\\\\Path
set _var4="QuotedPath\\\\Path%"

call :SetFQDP _var5 %_var1%\%_var2%
set _var5

call :SetFQDP _var5 %_var3%
set _var5

call :SetFQDP _var5 %_var4%
set _var5

@exit /b 0

@rem Set specified variable to a fully qualified drive\path name with no
@rem redundant backslashes. Convert all forward slashes to backslashes.
@rem Removes quotes.
:SetFQDP
@set %1=%~f2
@exit /b %_ERROR_SUCCESS_%

产品:

> test

>set _var1=\Dir1\\\\Dir2\

>set _var2=\Dir3\Dir4

>set _var3=Relative\\\\Path

>set _var4="QuotedPath\\\\Path"

>call :SetFQDP _var5 \Dir1\\\\Dir2\\\Dir3\Dir4

>set _var5
_var5=D:\Dir1\Dir2\Dir3\Dir4

>call :SetFQDP _var5 Relative\\\\Path

>set _var5
_var5=D:\TMP\Joseph\Relative\Path

>call :SetFQDP _var5 "QuotedPath\\\\Path"

>set _var5
_var5=D:\TMP\Joseph\QuotedPath\Path

请注意,如果未提供驱动器盘符,则使用当前驱动器。如果传入最后一个尾部斜杠,它将被保留。当前目录的完全限定路径始终以任何相对路径为前缀(不以“/”或“\”开头)。生成的路径不一定存在,因此您必须创建它或测试它是否存在。

为您整理所有内容:

@call :SetFQDP strDestPath=%LIBDIR%"\Libraries\python\win\"
@call :SetFQDP strPythonZipSourcePath=%CTEDIR%"\Libraries\python\win\Python27.zip

Call :UnZipFile %strDestPath% %strPythonZipSourcePath%
exit /b

@rem Set specified variable to a fully qualified drive\path name with no
@rem redundant backslashes. Convert all forward slashes to backslashes.
@rem Removes quotes.
:SetFQDP
@set %1=%~f2
@exit /b %_ERROR_SUCCESS_%
© www.soinside.com 2019 - 2024. All rights reserved.