Last token in batch variable

Why so complicated?

Solution for a string in a variable:

set var1=This is a String
for %%A in (%var1%) do set last=%%A

echo last=%last%

Solution for the result of an external command:

set xcmd=c:\monitor.exe -C custom_performance_counter -t %1 -w 80 -c 90
for /f "tokens=*" %%I in ('%xcmd%') do for %%A in (%%~I) do set last=%%A
echo last=%last%

@echo off

set var1=This is a String
set var2=%var1%
set i=0

:loopprocess
for /F "tokens=1*" %%A in ( "%var1%" ) do (
  set /A i+=1
  set var1=%%B
  goto loopprocess )

echo The string contains %i% tokens.

for /F "tokens=%i%" %%G in ( "%var2%" ) do set last=%%G

echo %last%

pause

Tags:

Batch File