Ben Blank
Ben Blank

Reputation: 56572

How can I URL-encode spaces in an NT batch file?

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.

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.

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

Upvotes: 4

Views: 9380

Answers (2)

Ben Blank
Ben Blank

Reputation: 56572

dbenham's solution is almost certainly preferable (being rather easier to read), but for the sake of completeness, here is an alternative solution:

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%

Upvotes: 2

dbenham
dbenham

Reputation: 130849

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

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

Upvotes: 3

Related Questions