Input:
set widget="a very useful item"
set widget
set widget=%widget:"=%
set widget
Output:
widget="a very useful item"
widget=a very useful item
Posted by jpluimers on 2018/02/06
Thanks [WayBack] Mr. Rick for the answer as this is exactly the bit I needed:
Input:
set widget="a very useful item" set widget set widget=%widget:"=% set widget
Output:
widget="a very useful item" widget=a very useful item
[WayBack] Removing double quotes from variables in batch file creates problems with CMD environment – Stack Overflow
This trick is convenient in cases like this:
set LocalHostsFile="%windir%\System32\drivers\etc\hosts"
set LocalHostsTemplate="%LocalHostsFile:"=%.template"
The above replaces ALL double quotes with nothing.
If you want to smart replace (like done when de-quoting CSV), you need a bit more complex code like described in [WayBack] batch file – Remove quotes from named environment variables in Windows scripts – Stack Overflow, where you basically have two options:
Both work because parameters used like %~x
do get their quotes removed; you cannot use that syntax on plain variables.
–jeroen
Peter Wright said
The syntax
set "widget=a very useful item"
is probably more useful. Here, the quotes delimit the string being assigned so that “editors” like notepad, which can leave spaces on the end of the line, don’t cause those extra (invisible) trailing spaces to be included in the value.
In principle, avoid including quotes in the values assigned to variables and insert them as required, for instance
for %%a in ( "%widget%" %widget%) do echo %%a
would show
a very useful item
a
very
useful
item
This evades batch string manipulation, which is a minefield.
Peter Wright said
Oops – that should be
echo %%~a
The
~
removes enclosing quotes for a metavariable.jpluimers said
The problem is that sometimes you do not have influence on the input variables because they come from elsewhere.
So I’ve adopted your comments to show the code as code blocks (so quotes become OK), then adopted the script in it to show what happens without and with the variable content itself having quotes:
Output:
There you see that using a tilde (
~
) with double-quoting variable content already having double quotes, the output inserts an extra terminating double quote.