## 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

Message
Author
pstein
Posts: 106
Joined: 09 Nov 2011 01:42

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

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: 1593
Joined: 06 Dec 2011 22:15
Location: México City, México

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

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: 2203
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?

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: 4098
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?

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.

pstein
Posts: 106
Joined: 09 Nov 2011 01:42

it works
thank you