Skip to main content

How to greppick the last number on a line in a bash script

edited tags
Link
Gilles 'SO- stop being evil'
  • 865.5k
  • 205
  • 1.8k
  • 2.3k
Source Link
Tim
  • 727
  • 1
  • 6
  • 9

How to grep the last number on a line in a bash script

I have output from the smartctl -a command; one of the lines looks like this:

9 Power_On_Hours 0x0032 100 100 000 Old_age Always - 301

I've placed this into a variable (if that's the correct term) in my bash script like this:

$SMARTCTL_OUTPUT=`smartctl -a /dev/sda`

I want to parse this so that only the number at the end of the line is returned to a variable, so in the above example 301 gets put into the variable $POWER_ON_HOURS.

I've tried using grep:

$SMARTCTL_OUTPUT=`smartctl -a /dev/sda | grep "Power_On_Hours"`

But this returns the other text (9 Power_On_Hours 0x0032 100 100 000 Old_age Always - ) that I'm not interested in.

Can I return just the number at the end of the line?