简体   繁体   中英

Remove trailing backslash from a path with batch

I have such a filename saved in a variable:

C:\Directory\Directory2\

And now I want to have this:

C:\Directory\Directory2

How to cut the last \ from the filename or the last character?

You can use substring expansion:

set "var=C:\Directory\Directory2\"
echo %var:~0,1%

obviously there might be a case where the last character is not \ . Therefore we rather test if it is the case, only then do we exclude it.

if "%var:~-1%" == "\" set "var=%var:~0,-1%"

Well, just don't; Removing the trailing backslash may change the target the path points to; think of C:\ – which points to the root directory of the drive, while C: points to the current directory of it.

The most reliable way of dealing with potential trailing backslashes is probably to append . , because C:\Directory\Directory2\ is equivalent to C:\Directory\Directory2\. , C:\Directory\Directory2 and C:\Directory\Directory2. , because all these paths point to exactly the same location.

If the suffix disturbs for cosmetic reasons, resolve it by a for loop after having appended . :

set "dirPath=C:\Directory\Directory2\"
for %%I in ("%dirPath%.") do echo "%%~fI"

The modifier ~f defines to resolve the path and also converts relative ones to full/absolute ones.

If the provided path may even end with \. or is something like C:. , appending another . would change its target; this however can be solved by another for loop before appending . :

set "dirPath=C:\Directory\Directory2\."
for %%J in ("%dirPath%") do for %%I in ("%%~fJ.") do echo "%%~fI"

Note that for resolves wildcards like ? and * .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM