6

I'm trying to use AWK to post the second row of last line of this command (the total disk space):

df --total

The command I'm using is:

df --total | awk 'FNR == NF {print $2}'

But it does not get it right. Is there another way to do it?

user2248259
  • 316
  • 1
  • 3
  • 13
  • You can also use `--output` to indicate the exact fields you want to print. For example, `df --output=size | tail -1`. More info in [How to select a particular column in linux df command](http://stackoverflow.com/a/28809214/1983854) – fedorqui Apr 07 '15 at 13:46

4 Answers4

17

You're using the awk variable NF which is Number of Fields. You might have meant NR, Number of Rows, but it's easier to just use END:

df --total | awk 'END {print $2}'
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • It works without `END` as well. Could you explain why `END` is required? – 030 Apr 07 '15 at 10:33
  • 1
    @185140777 because otherwise it will print the 2nd field from all the lines, whereas with `END` it just prints the 2nd field from the last line. – fedorqui Apr 07 '15 at 13:42
8

You can use tail first then use awk:

df --total | tail -1 | awk '{print $2}'
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
vahid abdi
  • 9,636
  • 4
  • 29
  • 35
  • 5
    @John, I'm at a loss as to why an extra process makes it less useful. Do you have some sort of resource quota on processes in your environment? :-) – paxdiablo Feb 23 '14 at 10:20
  • @paxdiablo: Yes absolutely we can use an extra process. But it's like the Useless Use Of Cat which I'm sure you can appreciate: if someone wants to do something in awk that is easy to do in awk, there's just no need to spawn another process. Same as if someone asks how to do something in Python and we know how to do it in Perl; we wouldn't suggest spawning a subprocess for that. But to each his own, maybe this is too old school (as awk itself is!). – John Zwinck Feb 23 '14 at 10:38
8

One way to do it is with a tail/awk combination, the former to get just the last line, the latter print the second column:

df --total | tail -1l | awk '{print $2}'

A pure-awk solution is to simply store the second column of every line and print it out at the end:

df --total | awk '{store = $2} END {print store}'

Or, since the final columns are maintained in the END block from the last line, simply:

df --total | awk 'END {print $2}'
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
4

awk has no concept of "this is the last line". sed does though:

df --total | sed -n '$s/[^[:space:]]\+[[:space:]]\+\([[:digit:]]\+\).*/\1/p'
glenn jackman
  • 238,783
  • 38
  • 220
  • 352