Bash – awk – combine two filters into one

awkbashscripting

I have this variable in a bash script on ubuntu 12.04 which is set to show the available MB on the root partition:

AV_MB=$(df -m |awk NR==2 |awk '{print $4}')

Is there an elegant way to combine these two awk expressions into one? Or a shorter way with sed or grep or cut?

Best Answer

Awk works on the "pattern {action}" model, so you can combine those two processes into a single and correct:

 df -m | awk 'NR==2 {print $4}'

This, however, is fragile as the second record could change (on my systems, the root record is the third row), so you can match on the final field of the record for the root filesystem, like so:

df -m | awk '$NF == "/" {print $4}'

which ensures your pattern matches wherever df prints /.

Related Question