2

Output of w | head -1 can give 2 different results for my machine:

16:34:42 up 32 days,  3:02,  1 user,  load average: 0.14, 0.11, 0.07
14:10:55 up 32 days, 39 min, 1 user, load average: 0.07, 0.13, 0.09

I need to get load average numbers (e.g. 0.07, 0.13, 0.09). How can I split the line by load average: string so that I can always get the load average numbers for two cases?

2
  • try this awk 'print $10 $11 $12'
    – RSFalcon7
    Oct 5, 2014 at 21:06
  • 2
    Incidental tip: use uptime to get this information instead of w | head -1. It's more direct, you don't have to filter the output.
    – Celada
    Oct 5, 2014 at 21:34

4 Answers 4

6

You can also use awk:

$ w | head -1 | awk '{print $10,$11,$12}'
0.80, 0.84, 0.93

Or, if the number of fields is variable, use:

$ w | head -1 | awk '{print $(NF-2),$(NF-1),$NF}'
0.81, 0.82, 0.91

Or, the much more elegant (thanks @Letitzia):

$ w | head -1 | awk -F "load average: " '{print $2}'

Sed:

$ w | head -1 | sed 's/.*load average: *//' 

Perl:

$ w | head -1 | perl -pe 's/.*load average: *//' 

or

$ w | head -1 | perl -lne '/.*load average: *(.*)/ && print $1' 

You can actually use colrm here but note that it removes "columns" which are defined as "a single character in a line". So, while it works for the example you have provided (because of the extra space) it won't if the number of columns changes further. Here, it's deleting columns 1 through 51

$ w | head -1 | colrm 1 51
6
  • or w | head -1 | awk -F "load average: " '{print $2}'
    – Lety
    Oct 5, 2014 at 22:26
  • @Letizia ooh, clever, I never think of setting FS to longer strings. Included in my answer, thanks.
    – terdon
    Oct 5, 2014 at 22:27
  • Why you need head -1? w | awk -F "load average: " '{print $2; exit}' Oct 6, 2014 at 4:14
  • @AvinashRaj you're quite right, I don't. I was focusing on the parsing so I just copied the OP's exact command.
    – terdon
    Oct 6, 2014 at 4:18
  • Oh, How w | head -1 command would give two lines as output? Oct 6, 2014 at 4:20
4

Normally I'd just use the ${parameter#word} bash parameter expansion. It expands $parameter, deleting word (which can be a pattern) from the start.

In your case, something like:

line=...
echo ${line#*load average: }

Making it a function:

get_load() {
    w | head -n 1 | { read -r line; echo ${line#*load average: }; }
}
3

If you want only last numbers you can use grep:

$ w | grep -Po 'load average: \K.*'
0.07, 0.13, 0.09
0

Another perl:

$ w | head -1 | perl -nle 'print +(split /load average:/)[-1]'
 0.42, 0.49, 0.63

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .