6

I have a batch file that needs to be passed a parameter that will include pipes and spaces. Because of the spaces, double quotes need to be attached to the parameter when passing it in. I need to strip off those double quotes and echo the parameter. Normally, using the ~ would let me do this, but I think something about the specific parameters I'm passing in causes a problem. If I do this:

[test1.bat]

call test2.bat "Account|Access Level|Description"

[test2.bat]

echo %1
echo %~1

And run test1.bat, I get this output:

"Account|Access Level|Description"
'Access' is not recognized as an internal or external command, operable program or batch file.

So how do I remove the double quotes and still have a usable variable?

SuperNES
  • 2,640
  • 9
  • 33
  • 49

2 Answers2

4

You could use delayed expansion, because it doesn't care about special characters.
The only problem is to get parameter content into a variable, as it can only transfer via a percent expansion.
But in your case this should work.

@echo off
setlocal DisableDelayedExpansion
set "str=%~1"
setlocal EnableDelayedExpansion
echo !str!

Remark, I disable first the delayed expansion, so the ! and ^ aren't modified by the expansion of %1

EDIT: The delayed expansion can be disabled or enabled with

setlocal DisableDelayedExpansion
setlocal EnableDelayedExpansion

If enabled, it adds another way of extending variables (!variable! instead of %variable%), primary to prevent the parenthesis block effect of variables (described at set /?).

But the expansion with !variable! also prevents the content of any further parsing, because the delayed expansion is the last phase of batch line parsing.
In detail it is explained at how does the windows command interpreter cmd exe parse scripts

Community
  • 1
  • 1
jeb
  • 70,992
  • 15
  • 159
  • 202
  • it worked! thank you so much! can you tell me why it worked? what am i doing when i disable or enable "delayed expansion"? – SuperNES Mar 09 '11 at 15:18
  • How would you pass a single double quote into this? Whenever I try to call a batch file quoting it like `.\blah.cmd "asdf"" 123"` the `echo !str!` outputs two double quotes instead of one. – binki Mar 17 '17 at 17:42
1
@echo off
if "%~2"=="" (
    call %0 "Account|Access Level|Description" dummy
) ELSE (
    setlocal ENABLEEXTENSIONS
    for /F "tokens=*" %%A IN ("%~1") DO @echo.%%A
)

Not exactly pretty, but it works. Dealing with special characters is always a pain in batch files...

Anders
  • 83,372
  • 11
  • 96
  • 148
  • How would you pass a literal double-quote into this? When I try (by `.\play2.cmd "a b"" c" dummy`) I get two double quotes echoed instead of 1. – binki Mar 17 '17 at 17:38