如何对NT批处理文件中的空格进行URL编码? [英] How can I URL-encode spaces in an NT batch file?

查看:90
本文介绍了如何对NT批处理文件中的空格进行URL编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很不幸使用一个程序,该程序要求将传入的所有文件名都作为有效的URL. (不,我不知道为什么.)我不必每次都拖放到命令行并手工创建file: URL,而是将一个批处理文件放在一起,可以将从Windows拖放的文件拖放到该文件上. GUI.

I have the misfortune of working with a program which requires all filenames passed into it to be valid URLs. (No, I don't know why.) Rather than having to drop to the command line and hand-craft file: URLs each time, I'm throwing together a batch file onto which I can simply drop files dragged from the Windows GUI.

完整,正确的URL编码器超出了我的需求或兴趣(无论如何,应用程序阻塞的大多数字符在Windows文件名中都无效),但是我确实需要解决的两种情况是反斜杠和空格.反斜杠可以通过变量替换语法(SET URL=%URL:\=/%)轻松处理,但是空格很棘手-%对于URL和批处理文件都是特殊的.

A full, proper URL encoder is beyond my needs or interest (most of the characters the app chokes on aren't valid in Windows filenames, anyway), but the two cases I do need to solve are backslashes and spaces. Backslashes are easily handled by variable replacement syntax (SET URL=%URL:\=/%), but spaces are tricky — % is special for both URLs and batch files.

我不熟悉的两种类型的批量转义(^%%%)都不允许变量替换按预期方式运行,并且我没有任何成功的Google搜索解决方案.任何一批大师都可以帮助我吗?

Neither type of batch escaping I'm familiar with (^%, %%) allows the variable replacement to behave as desired and I haven't had any success Googling a solution. Can any batch gurus help me out?

这是我到目前为止所拥有的:

Here's what I have so far:

@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

推荐答案

旁注-我相信您希望使用%~f1而不是%~dp1

Side note - I believe you want %~f1 instead of %~dp1

您需要切换到延迟扩展.

You need to switch over to delayed expansion.

@echo off
setlocal enableDelayedExpansion

set "URLPATH=file:/%~f1"
set "URLPATH=!URLPATH:\=/!"
set "URLPATH=!URLPATH: =%%20!"
stupidapp.exe !URLPATH!

endlocal

如果您的任何文件名碰巧包含!字符,则需要做更多的工作,因为如果启用了延迟扩展,则在%1扩展时它将损坏.

A bit more work is required if any of your file names happen to contain the ! character because it will be corrupted when %1 is expanded if delayed expansion is enabled.

@echo off
setlocal disableDelayedExpansion
set "URLPATH=file:/%~f1"
setlocal enableDelayedExpansion
set "URLPATH=!URLPATH:\=/!"
set "URLPATH=!URLPATH: =%%20!"
stupidapp.exe !URLPATH!

endlocal
endlocal

这篇关于如何对NT批处理文件中的空格进行URL编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆