Reputation: 17
I want to get last word from a sentence or file path
I tried solutions from other articles and forums but can't seem to figure it out. here is what I have so far
@echo off
set a="C:\Some\Random\File\Path.txt"
echo %a%
set b=%a:\= %
echo %b%
for /f "tokens=*" %%a in (%b%) do @echo %%a %%b %%c
pause
All I need is the last word of what ever file path I put in %a%
Upvotes: 0
Views: 515
Reputation:
Just to answer specifically on your question:
@echo off
set "a=C:\Some\Random\File\Path.txt"
for %%i in (%a%) do echo %%~nxi
pause
Also see how I used the double quotes on the set
ting of the variable, This allows us to get rid of any wanted whitespace after the value, and also if we add the quotes after the equal, they become part of the value, which is not what we really want.
To understand the variable references, for from cmdline for /?
I suggest you also see set /?
Additionally, based on your comment, if you want to set it as a viarble, simply do it :)
@echo off
set "a=C:\Some\Random\File\Path.txt"
for %%i in (%a%) do set variablename=%%~nxi
echo %variablename%
pause
Upvotes: 1
Reputation:
While Gerhards solution IS preferable (for path), your approach wasn't that bad.
You just have to use a simple for,
so it iterates over the space seperated elements which therefor have to be unquoted.
Repeatedly setting the same variable will have the last value/word persisting.
:: Q:\Test\2019\01\18\SO_54246604.cmd
@echo off
set "a=C:\Some\Random\File\Path.txt"
echo %a%
for %%a in (%a:\= %) do Set "b=%%a"
echo %b%
pause
> SO_54246604.cmd
C:\Some\Random\File\Path.txt
Path.txt
Upvotes: 1