adom
adom

Reputation: 61

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

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 "^"" == "^-"

Upvotes: 2

Views: 110

Answers (2)

Stephan
Stephan

Reputation: 56180

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

Upvotes: 0

jeb
jeb

Reputation: 82287

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!" == "-" ...

Upvotes: 1

Related Questions