Windows批处理文件反斜杠问题

3pvhb19x  于 2023-08-07  发布在  Windows
关注(0)|答案(1)|浏览(276)

我有一个简单的批处理文件,它将参数作为命令执行,例如
runner.bat

@echo off
setlocal enabledelayedexpansion

set title=%1
set compiler=%2
set options=%~3
set "src_args="

for %%i in (%*) do (
    if not %%i==!title! (
        if not %%i==!compiler! (
            if not %%~i==!options! (
                set SRC_ARGS=!src_args! %%i
            )
        )
    )
)

cmd /c %compiler% %options% %SRC_ARGS%

pause

exit /b 0

字符串
且当执行它时
这很好

runner.bat "my title" python -b -B "C:\DEV\my app2 py\main.py" "hello world" one


错误,原因是\”

runner.bat "my title" python -b -B "C:\DEV\my app2 py\main.py" "\\"hello world" one


脚本运行正常,但在传递包含\”的参数时出现问题。对于python脚本,我尝试用”转义引号,但我希望\”被转义
如何解决这一问题?

rkue9o1l

rkue9o1l1#

你可以使用^字符来转义反斜杠,类似这样:

@echo off
setlocal enabledelayedexpansion

set "title=%~1"
set "compiler=%~2"
set "options=%~3"
set "src_args="

for %%i in (%*) do (
    if not "%%~i"=="!title!" (
        if not "%%~i"=="!compiler!" (
            if not "%%~i"=="!options!" (
                set "arg=%%~i"
                if "!arg:~0,1!"=="\" (
                    set "arg=!arg:~1,-1!"
                )
                set "SRC_ARGS=!src_args! !arg!"
            )
        )
    )
)

cmd /c "%compiler%" "%options%" %SRC_ARGS%

pause

exit /b 0

字符串
现在,运行如下脚本:

runner.bat python -b -B "C:\DEV\my app2 py\command.txt" "\"hello world\"" \"myarg

更新

ok,我使用~修饰符和%%i来删除参数中的任何引号,看看这个:

@echo off
setlocal enabledelayedexpansion

set title=%1
set compiler=%2
set options=%~3
set "src_args="

for %%i in (%*) do (
    if not "%%i"=="!title!" (
        if not "%%i"=="!compiler!" (
            if not "%%~i"=="!options!" (
                set "arg=%%~i"
                set "arg=!arg:^\"=\"!"
                set "arg=!arg:'=\'!"
                set "arg=!arg:^=^^!"
                set "arg=!arg:$=$!"
                set SRC_ARGS=!src_args! !arg!
            )
        )
    )
)

cmd /c %compiler% %options% %SRC_ARGS%

pause

exit /b 0

相关问题