我不幸使用一个程序,该程序要求传入其中的所有文件名都是有效的URL。 (不,我不知道为什么。)我不是每次都要放到命令行并手工制作file:
个URL,而是将一个批处理文件放在一起,我可以简单地拖放文件Windows GUI。
完整,正确的URL编码器超出了我的需要或兴趣(应用程序阻塞的大多数字符在Windows文件名中无效),但我需要解决的两个案例是反斜杠和空格。可以通过变量替换语法(SET URL=%URL:\=/%
)轻松处理反斜杠,但空格很棘手 - %
对于URL和批处理文件都是特殊的。
我不熟悉的任何类型的批量转义(^%
,%%
)都允许变量替换行为符合要求而且我没有取得任何成功Google搜索解决方案。任何批量专家可以帮助我吗?
这是我到目前为止所拥有的:
@ECHO OFF
SETLOCAL
SET URLPATH=file:/%~dp1
SET URLPATH=%URLPATH:\=/%
REM none of these work
REM SET URLPATH=%URLPATH: =%20%
REM SET URLPATH=%URLPATH: =%%20%
REM SET URLPATH=%URLPATH: =^%20%
REM works; I just need to figure out how to generate it
SET URLPATH=file:/C:/Documents%%20and%%20Settings/bblank/example.dat
stupidapp.exe %URLPATH%
ENDLOCAL
答案 0 :(得分:3)
旁注 - 我相信您需要%~f1
而不是%~dp1
您需要切换到延迟扩展。
@echo off
setlocal enableDelayedExpansion
set "URLPATH=file:/%~f1"
set "URLPATH=!URLPATH:\=/!"
set "URLPATH=!URLPATH: =%%20!"
stupidapp.exe !URLPATH!
endlocal
如果您的任何文件名恰好包含!
字符,则需要进行更多工作,因为如果启用延迟扩展,%1将被展开时会损坏。
@echo off
setlocal disableDelayedExpansion
set "URLPATH=file:/%~f1"
setlocal enableDelayedExpansion
set "URLPATH=!URLPATH:\=/!"
set "URLPATH=!URLPATH: =%%20!"
stupidapp.exe !URLPATH!
endlocal
endlocal
答案 1 :(得分:2)
SET URLPATH=file:/%~dp1
SET URLPATH=%URLPATH:\=/%
REM for each space in the path, split the path into the portions before and after
REM that space, then join them with an escaped space
:ESCAPE_SPACE
SET TRAILING=%URLPATH:* =%
CALL SET URLPATH=%%URLPATH: %TRAILING%=%%
SET URLPATH=%URLPATH%%%20%TRAILING%
IF NOT "%URLPATH%"=="%URLPATH: =%" GOTO ESCAPE_SPACE
stupidapp.exe %URLPATH%