Page 1 of 1

How to I replace " by ' " (at the start and end of a string in a variable)? Doubling Backslashes?

Posted: 28 Nov 2018 05:15
by pstein
Assume I have a variable with a double quote enclosed string inside. Most simplified by a manual assigment like

set myfile="D:\foo\bar\aaa\bbb.txt"

How can I most easily replace the two enclosing " by ' ?

How can I most easily replace the embedded single backslashes \ by double backslashes?

Afterwards the variable content should lokk like:

'D:\\foo\\bar\\aaa\\bbb.txt'

Thank you
Peter

Re: How to I replace " by ' " (at the start and end of a string in a variable)? Doubling Backslashes?

Posted: 28 Nov 2018 07:09
by Aacini

Code: Select all

for /F %%a in (%myfile:\=\\%) do set "myfile='%%a'"
If the file name may contain spaces, just add "delims=" option to the FOR /F command.

Antonio

Re: How to I replace " by ' " (at the start and end of a string in a variable)? Doubling Backslashes?

Posted: 28 Nov 2018 09:13
by dbenham
The body of the question asks for a result of 'D:\\foo\\bar\\aaa\\bbb.txt', but the title implies he is looking for ' "D:\\foo\\bar\\aaa\\bbb.txt" '. (Note extra space added to differentiate between the single and double quotes)

To strip the double quotes, just modify Aacini's answer by one additional ~ character

Code: Select all

for /F "delims=" %%a in (%myfile:\=\\%) do set "myfile='%%~a'"
Assuming your string does not contain any * or ? wildcards, then you can ditch the /F option and use a simple FOR. The advantage of this is you no longer need to worry about spaces in the string:

Code: Select all

for %%a in (%myfile:\=\\%) do set "myfile='%%~a'"
Dave Benham

Re: How to I replace " by ' " (at the start and end of a string in a variable)? Doubling Backslashes?

Posted: 28 Nov 2018 13:33
by Squashman
If you have control over the code why would you assign the double quotes to the variable in the first place. That has never been a best practice on this forum.

Re: How to I replace " by ' " (at the start and end of a string in a variable)? Doubling Backslashes?

Posted: 29 Nov 2018 01:59
by pstein
it works
thank you