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?

1

4 Answers 4

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}' 
Sign up to request clarification or add additional context in comments.

2 Comments

It works without END as well. Could you explain why END is required?
@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.
8

You can use tail first then use awk:

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

2 Comments

@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: 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!).
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}' 

1 Comment

You do not need to store $2 an a variable, just print it in an end section.
4

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

df --total | sed -n '$s/[^[:space:]]\+[[:space:]]\+\([[:digit:]]\+\).*/\1/p' 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.