Search code examples
stringvariablestcleggdrop

Reading last whole word from variable


I am currently making a script that manipulates several files, and I am trying to read the last whole word from a variable ($pio).

The string is variable in length and word count and is set to $pio in the start of the function.

I have tried to read the last word in the line/variable separated by a whitespace with "strip" but this far I have only been able to read by character count.

Is it possible to read the whole last word of the string and parse it into a new variable?


Solution

  • You can split the string and then take the last index:

    set lastWord [lindex [split $pio] end]
    

    Or if you don't mind using a little regexp, you can use something like this:

    regexp -- {\S+$} $pio lastWord
    

    \S+ is an expression to match at least 1 non-space character, and $ makes sure that this match occurs at the end of the string. The match will be stored a variable named lastWord.

    codepad demo