I'm trying to search a string (entered by the user when prompted for a path) for a trailing quote and delete it if found.
The problem: I have a bat file that prompts the user to enter a filename and path (the first is typically done via drag/drop.) If the user enters a destination path enclosed in quotes because it contains spaces, my resulting command will look like this: compress.exe "c:\source path\"destination.zip"
That extra quote in the middle needs to go. I've found plenty of ways to search a file for a string, and I found this post here on StackOverflow that seems to apply, but doesn't seem to work in my situation.
I tried the command at the above linked path, telling it to search for \"
instead of bcd
, but the code expects the string it's searching to have been passed to it (as a switch) upon execution, and when I try to modify the command to search srcpath instead, the bat fails. I also tried this:
if "!srcpath:~-1"=="\"" set srcpath=!srcpath:~0,-1!
This results in: "The syntax of the command is incorrect."
How can I search a string for a trailing quote and trim it? Every method I can find doesn't seem to work when the character being searched for is the quote (slash quote: \"
).
I use a SLOPPY batch trick when working with paths just for this reason. There are more elegant ways but this works just as well and I don't ever have to remember how I pulled it off.
First of all, 90% of the time.. we just want ALL quotes stripped.. that would just be:
set srcpath=%srcpath:"=%
Then tack quotes on to the front and back of your new concatenated path string.
But if you REALLY only want the trailing one.. here is my stupid bash trick..
1. Add a "? to the end of your string
2. Then delete ""? from that string
3. Then delete "? from that string
Wella! Never fails! The trick here is that a question mark isn't a valid path char.
:: SAMPLE -- Just a trailing quote removed
set srcpath="c:\source path\"
set srcpath=%srcpath%"?
set srcpath=%srcpath:""?=%
set srcpath=%srcpath:"?=%
echo srcpath=%srcpath%
::You can use the SAME TRICK to remove a trailing backslash