Reputation: 171
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?
Upvotes: 3
Views: 8537
Reputation: 1771
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
Upvotes: 0
Reputation: 3683
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
Upvotes: 0
Reputation: 11
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
.
Upvotes: 1
Reputation: 70923
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
Upvotes: 8