Home > Net >  How to compare characters in Batch script when left hand side is double quote
How to compare characters in Batch script when left hand side is double quote

Time:06-24

I have Windows Batch code where I'm trying to test if the first character of value is a hyphen but the code fails when the first character of value is a double quote. (value is coming from elsewhere in the real code.)

set value=""This is a test""
set arg="%value%"
set prefix=%arg:~1,1%
if "%prefix%" == "-" ...

Evaluates to

if """ == "-"

and generates The syntax of the command is incorrect. I tried inserting a caret into both sides of the equality check

if "^%prefix%" == "^-" ...

but that generates the same error with

if "^"" == "^-"

CodePudding user response:

You can use the caret to escape a single character, like

if ^"^%prefix%^" == "-" ...

The trick is to escape the quotes, too, else the inner caret has no special meaning.

This can't work for more than one character, but you could switch to the even simple delayed expansion. It's expansion is always safe.

setlocal EnableDelayedExpansion
set "value="This is a test""
set "arg=!value!"
set "prefix=!arg:~1,1!"
if "!prefix!" == "-" ...

CodePudding user response:

test if the first character of value is a hyphen

Another approach (using the original string, no additional variables):

@echo off
setlocal EnableDelayedExpansion

set value1=-correct
set value2=xfail
set value3="fail
set value
echo ---------
echo !value1!|findstr /bc:"-" >nul && echo hyphen || echo something else
echo !value2!|findstr /bc:"-" >nul && echo hyphen || echo something else
echo !value3!|findstr /bc:"-" >nul && echo hyphen || echo something else
  • Related