CrazyCoder
CrazyCoder

Reputation: 780

trim last word from string from commandline in linux

I have tried to trim last word from string but not able to get the word.

Please see below I tried in two way but no luck

$ test="COUNT(*) ---------- 10"   <-string
$ echo $test
COUNT(*) ---------- 10
$ echo ${test##*:}    <-First way
COUNT(*) ---------- 10   <-output
$ echo $test | rev | cut -d: -f1 | rev   <-second way
COUNT(*) ---------- 10 <-output

I need o/p as 10.

Upvotes: 1

Views: 301

Answers (2)

user1934428
user1934428

Reputation: 22225

last_word=${test##* }

The ## selects a maximum string to remove, and the string to be removed must end with a space.

Upvotes: 3

Raman Sailopal
Raman Sailopal

Reputation: 12867

echo ${test##* }

From man bash:

   ${parameter##word}
          Remove matching prefix pattern.  The word is expanded to produce
          a pattern just as in pathname expansion.  If the pattern matches
          the beginning of the value of parameter, then the result of  the
          expansion  is  the expanded value of parameter with the shortest
          matching pattern (the ``#'' case) or the longest  matching  patâ
          tern  (the  ``##''  case)  deleted.  If parameter is @ or *, the
          pattern removal operation is applied to each positional  parameâ
          ter in turn, and the expansion is the resultant list.  If paramâ
          eter is an array variable subscripted with @ or *,  the  pattern
          removal  operation  is  applied  to  each member of the array in
          turn, and the expansion is the resultant list.

Upvotes: 1

Related Questions