Last token in batch variable

后端 未结 5 2040
死守一世寂寞
死守一世寂寞 2020-12-11 03:54

In a batch file, how can I get the last token in a variable regardless of whether it is a number or a word and regardless of how many tokens/words there are in the variable.

相关标签:
5条回答
  • 2020-12-11 04:08

    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%
    
    0 讨论(0)
  • 2020-12-11 04:14
    @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
    
    0 讨论(0)
  • 2020-12-11 04:14

    Some code golf on Eli's answer.

    @echo off
    
    set var1=This is a String
    REM token_string will be manipulated each loop
    set token_string=%var1%
    
    :find_last_loop
    for /F "tokens=1*" %%A in ( "%token_string%" ) do (
      set last=%%A
      set token_string=%%B
      goto find_last_loop)
    
    echo %last%
    
    pause
    

    And to find something with ':' delimiters...

    for /F "tokens=1* delims=:" %%A in ( "%token_string%" ) do (
    
    0 讨论(0)
  • 2020-12-11 04:16

    If you insist on passing only a single argument, then you can use a subroutine:

    @echo off
    call :get_last %~1
    echo.%last%
    goto :eof
    
    rem get_last tokens...
    :get_last
      set last=%1
      shift
      if [%1]==[] goto :eof
      goto get_last
    

    However, if you're just passing any number of arguments to the batch, then you can do that directly:

    @echo off
    :l
    set last=%1
    shift
    if [%1]==[] goto pl
    goto l
    :pl
    echo %last%
    

    Side note: You rarely want to put exit in a batch file, as it exits the command processor, not the batch. That's kinda annoying if you use it directly from the shell or from other batch files.

    0 讨论(0)
  • 2020-12-11 04:16

    if the tokens are separated by spaces, the last token is:

    set b=command to grab the last token
    for %i in (%b: =\%) do echo %~ni
    
    0 讨论(0)
提交回复
热议问题