Handling backslash and directory names with spaces in batch files

This is a variation of this question: Remove trailing slash from input file file

but it is subtly different, so I don’t think it’s a hoax.

I am having trouble creating this work with directories that have spaces (running WinXP).

:START
@echo What folder do you want to process? (Provide a path without a closing backslash)
set /p datapath=

::Is string empty?
IF X%datapath% == X GOTO:START

::Does string have a trailing slash? if so remove it 
IF %datapath:~-1%==\ SET datapath=%datapath:~0,-1%

echo %datapath%

It processes:

c:\

(strip it to c :)

But if you enter:

c:\test space

error: "space was unexpected at this time."

If you try to enter:

"c:\test space"

You get the same error.

I thought this would include a strategically placed "or two on this line:

IF %datapath:~-1%==\ SET datapath=%datapath:~0,-1%

But I’m out of luck.

Any ideas?

+3
source share
1 answer

, , .

:START
setlocal EnableDelayedExpansion
@echo What folder do you want to process? (Provide a path without a closing backslash)
set /p datapath=

::Is string empty?
IF X!datapath! == X GOTO:START

::Does string have a trailing slash? if so remove it 
IF !datapath:~-1!==\ SET "datapath=!datapath:~0,-1!"

echo !datapath!

, , , - .

+2

Source: https://habr.com/ru/post/1796365/


All Articles