2

I am working on a batch script, and I need a way to remove the lowest-level directory from a full path string. So for example, if I have:

C:/dir1/dir2/dir3

I would like my batch script to return "dir3." This string, C:/dir1/dir2/dir3 is passed in by the user and set as the variable "FullPath".

I looked over the answer here, which appeared to be a similar problem, but the solutions there didn't make any use of delimiters. And, the closest I've gotten to solving this is this code:

for /f "tokens=(some number) delims=\" %%a in ("%FullPath%") do echo Token=%%a

...this can echo any token I specify (I will eventually be setting this token to a variable, but I need to get the right one first), but I don't know how many tokens there will be, and I always want the last one in the string, as following the "\" character.

How can I edit this line of code to return the final token in the string?

Community
  • 1
  • 1

4 Answers4

7
for %%a in ("%fullpath%\.") do set "lastPart=%%~nxa"

That is, use a for loop to get a reference to the full path and from it retrieve the name and extension of the last element

MC ND
  • 69,615
  • 8
  • 84
  • 126
1

I solved in this way:

for %%x in (%fullpath:\= %) do set last=%%x

This uses the same logic as the last answer but it does the standard for loop changing the delimiter from \ to space with the %var:=% syntax. It's a trick to obtain the effect of for /f "delims=\", using for instead of for /f which does not loop like plain for.

unwind
  • 391,730
  • 64
  • 469
  • 606
0

if the tokens are separated/delimited by forward slashes ("/"), the last token is:

set b=C:/dir1/dir2/dir3
for %i in (%b:/=\%) do echo %~ni
Zimba
  • 2,854
  • 18
  • 26
0

I had a similar case, where I wanted only the name of the file from a link address. This seemed to do the job:

@echo off
set PYZIP=https://www.python.org/ftp/python/3.8.6/python-3.8.6-embed-win32.zip

for %%x in (%PYZIP:/= %) do set PYZIP_FILE=%%x
echo %PYZIP_FILE%

returns: python-3.8.6-embed-win32.zip

RexBarker
  • 1,456
  • 16
  • 14
  • Your solutions have some drawbacks. It's slow, it fails for files like `C:\Program Files (x86)\file.txt` or `C:\temp\my file with spaces.txt`. Better use the modifiers `%%~nx` – jeb Jan 20 '21 at 14:47
  • true, but this is only directed at web link type addresses where there will not be spaces – RexBarker Jan 20 '21 at 14:48
  • That makes it a solution for your partial problem only and it still fails when there are other characters inside the link, like comma or semicolon. – jeb Jan 20 '21 at 14:56