[ACCEPTED]-Remove quotes from named environment variables in Windows scripts-quotes

Accepted answer
Score: 40

echo %myvar:"=%

0

Score: 34

This is not a limitation of the environment 7 variable, but rather the command shell.

Enclose 6 the entire assignment in quotes:

set "myvar=http://example.com?foo=1&bar="

Though if 5 you try to echo this, it will complain as 4 the shell will see a break in there.

You 3 can echo it by enclosing the var name in 2 quotes:

echo "%myvar%"

Or better, just use the set command 1 to view the contents:

set myvar
Score: 11

While there are several good answers already, another 2 way to remove quotes is to use a simple 1 subroutine:

:unquote
  set %1=%~2
  goto :EOF

Here's a complete usage example:

@echo off
setlocal ENABLEDELAYEDEXPANSION ENABLEEXTENSIONS

set words="Two words"
call :unquote words %words%
echo %words%

set quoted="Now is the time"
call :unquote unquoted %quoted%
echo %unquoted%

set word=NoQuoteTest
call :unquote word %word%
echo %word%

goto :EOF

:unquote
  set %1=%~2
  goto :EOF
Score: 9

This works

for %a in (%myvar%) do set myvar=%~a

I would also use this if I wanted 2 to print a variable that contained and ampersand 1 without the quotes.

for %a in ("fish & chips") do echo %~a
Score: 3

To remove only beginning and ending quotes 4 from a variable:

SET myvar=###%myvar%###
SET myvar=%myvar:"###=%
SET myvar=%myvar:###"=%
SET myvar=%myvar:###=%

This assumes you don't have 3 a ###" or "### inside your value, and 2 does not work if the variable is NULL.

Credit 1 goes to http://ss64.com/nt/syntax-esc.html for this method.

Score: 2

Use delayed environment variable expansion 1 and use !var:~1,-1! to remove the quotes:

@echo off
setlocal enabledelayedexpansion
set myvar="http://example.com?foo=1&bar="
set myvarWithoutQuotes=!myvar:~1,-1!
echo !myvarWithoutQuotes!
Score: 1

Use multiple variables to do it:

set myvar="http://example.com?foo=1&bar="

set bar=true

set launch=%testvar:,-1%%bar%"

start iexplore %launch%

0

Score: 0
@echo off
set "myvar=http://example.com?foo=1&bar="
setlocal EnableDelayedExpansion
echo !myvar!

This is because the variable contains special 1 shell characters.

More Related questions