85

I have a batch file that I want to improve. Instead of requiring a user to provide a folder path without a trailing slash, is there an easy way for me to just remove the last character from the path if there is a slash on the end?

: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 %datapath:~-1%==\ GOTO:START
akf
  • 38,619
  • 8
  • 86
  • 96
Brook
  • 1,095
  • 1
  • 10
  • 15

1 Answers1

156

you can use syntax similar your evaluation:

::Does string have a trailing slash? if so remove it 
IF %datapath:~-1%==\ SET datapath=%datapath:~0,-1%
akf
  • 38,619
  • 8
  • 86
  • 96
  • Thanks! I just ran into such an issue, and this was the perfect answer. – gregturn Sep 07 '12 at 00:55
  • 8
    You can also consider just adding a `.` in the case of a trailing slash. A lil' shorter than the substring syntax. – Barett Sep 03 '15 at 16:44
  • 2
    What if the path was `"C:\My Folder\"` ? – BaSsGaz Sep 13 '17 at 12:00
  • 4
    Conversely, if you want to ensure that there IS a backslash on the end, it would be: ```IF NOT "%datapath:~-1%"=="\" SET "datapath=%datapath%\"``` to force it. The quotes protect internal spaces. – Jesse Chisholm Feb 09 '18 at 16:38
  • 4
    If there are spaces in the path then you need to be careful with quotes. If `%datapath%` contains leading and trailing quotes then you can use `IF "%datapath:~-2,-1%"=="\" SET datapath="%datapath:~1,-2%"` – yoyo Jun 11 '18 at 22:50
  • Worth a read: https://stackoverflow.com/a/25853380/1540350 <- This also works for arguments – Martin Braun Aug 11 '22 at 12:22