Home > Enterprise >  Batch files (cmd) : removing last "\" in directory name [closed]
Batch files (cmd) : removing last "\" in directory name [closed]

Time:10-04

I write some .bat files. In them, I need to get the current directory without the remaining "\". I use this kind of script :

@ECHO OFF
SET ROOT_DIR=%~dp0
@ECHO ROOT_DIR IS "%ROOT_DIR%"
REM Remove last "\"
if "%ROOT_DIR:~-1%" == "\" (
  SET ROOT_DIR=%ROOT_DIR:~0,-1%
)
@ECHO ADAPTED ROOT_DIR IS "%ROOT_DIR%"
PAUSE

It generally works. For example, if I put such a file in D:\test, the result is :

ROOT_DIR IS "D:\test\"
ADAPTED ROOT_DIR IS "D:\test"
Appuyez sur une touche pour continuer...

However, for some reason I don't understand, there is a problem when the folder name ends with ")", like "C:\Program Files (x86)". In that folder, it removes the last ")" too, which is a behaviour I don't want :

ROOT_DIR IS "C:\Program Files (x86)\"
ADAPTED ROOT_DIR IS "C:\Program Files (x86"
Appuyez sur une touche pour continuer...

Does anyone have any idea about how to solve that problem, i.e. removing only the last "\" in folder name, whatever the folder name, and without removing the parenthesis ?

Thank you by advance for your answers.

CodePudding user response:

@Mofi had the right answer : I should use quotes around the SET ROOT_DIR instructions. That way, the parenthesis are kept (no interpretation). I tested on various folders and it did work. So thank you very much @Mofi for the solution.

And thank you @phuclv concerning "DOS batch file", I will keep that in mind (I updated the title).

--Edit--

So the right code becomes

@ECHO OFF
SET "ROOT_DIR=%~dp0"
@ECHO ROOT_DIR IS "%ROOT_DIR%"
REM Remove last "\"
if "%ROOT_DIR:~-1%" == "\" (
  SET "ROOT_DIR=%ROOT_DIR:~0,-1%"
)
@ECHO ADAPTED ROOT_DIR IS "%ROOT_DIR%"
PAUSE

This kind of code is a base to then use recursive algorithms that will enter sub-directories (sub-sub-directories and so on) by adding "\" then sub-directory name and do that at any desired depth. So, in my case, it is useful even when the parent directory is directly the drive letter itself.

  • Related