Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last token from string in batch script

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?

like image 466
JayneCobb's_HatDesigner Avatar asked May 29 '26 05:05

JayneCobb's_HatDesigner


1 Answers

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

like image 102
MC ND Avatar answered May 31 '26 08:05

MC ND