Can someone explain me what happens here?
uptime | awk -F: '{print $NF}'
- -F: field separator
- $NF: number of fields in the current line
I don't understand why this command result in the same result as
uptime | awk -F: '{print $5}'
The option -F
(--field-separator fs
) -F:
makes :
the input field separator.
We could take the output of an example uptime
and split it into fields separated by :
:
09:03:24 up 32 days, 1:32, 3 users, load average: 0.04, 0.09, 0.08
-- -- ----------------- --------------------------- -----------------
1 2 3 4 5
It's easy to say that the fields 1-4 are pretty pointless by themselves, but the 5th field gives us just the load averages. But this doesn't work all the time, as an hour earlier it would have been the 4th field:
08:03:24 up 32 days, 32 min, 3 users, load average: 0.00, 0.00, 0.00
-- -- --------------------------------------------- -----------------
1 2 3 4
Here, the $NF
comes to help, as it will always give the number of fields: in the first case it would have been equal to $5
, but in the second case $4
.
Putting it all together, | awk -F: '{print $NF}'
always gives everything after the last :
.
Good explanation by Esa Jokinen, I am giving you one example not to use specific column number in case of uptime (Examples are from MAC system).
$ uptime
16:12 up 25 days, 2:48, 15 users, load averages: 3.41 3.20 3.11
Check how many fields.
$ uptime | awk -F: '{print NF}'
4
Now if you use $NF it will gives you desired results but $5 will not.
$ uptime | awk -F: '{print $NF}'
3.96 3.31 3.15
The -F fs
option defines the input field separator to be the regular expression fs
. So here :
is just a separator to divide into columns.