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

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
pstein
Posts: 125
Joined: 09 Nov 2011 01:42

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

#1 Post by pstein » 28 Nov 2018 05:15

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

Aacini
Expert
Posts: 1914
Joined: 06 Dec 2011 22:15
Location: México City, México
Contact:

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

#2 Post by Aacini » 28 Nov 2018 07:09

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

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

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

#3 Post by dbenham » 28 Nov 2018 09:13

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

Squashman
Expert
Posts: 4486
Joined: 23 Dec 2011 13:59

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

#4 Post by Squashman » 28 Nov 2018 13:33

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.


Post Reply