1

I need to extract the available memory from the output free and I thought I would use awk and came up with something like free | awk '{print $4}'. Which gives me an output like:

$ free | awk '{print $4}'
shared
365296
1273812
3931364

mind, the title shared isn't the title of these numbers, the numbers are from free (/usr/bin/free has no title in the first column, thus the numbers for free appear in the 4th column where the title reported is from the 5th). However, having this, how do I only return the second line? I'm not interested in the rest for now.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
stdcerr
  • 13,725
  • 25
  • 71
  • 128

2 Answers2

8
free | awk 'NR==2 {print $4}'

NR, is the ROW/Line number

iamauser
  • 11,119
  • 5
  • 34
  • 52
  • +1 but add `;exit` after `$4` since the OP only wants the 2nd line, not the 2nd and subsequent lines. – Ed Morton Aug 19 '13 at 19:08
  • shoudn't `;exit` be redundant in this case ? The above command will only print the second line; Note `NR==2`. – iamauser Aug 19 '13 at 19:12
  • It'll produce the correct output, it's just inefficient since it'll continue parsing the rest of the input after the 2nd line. I don't know how many lines of output `free` can produce so that may or may not be a concern. – Ed Morton Aug 19 '13 at 19:15
  • Most linux system shows about 4 lines when `free` is typed, so not losing much here. – iamauser Aug 19 '13 at 19:19
  • OK, I'm on Solaris and cygwin and don't have a command named `free` either place so I'd no idea what it outputs. – Ed Morton Aug 19 '13 at 19:25
1

Just figured it out myself, it can be accomplished using:

$ free | awk '{print $4}'| head -2| tail -1
stdcerr
  • 13,725
  • 25
  • 71
  • 128
  • -1 for posting an answer to your own question instead of updating your question with your best attempt at an answer and asking for something better or just deleting your question if you think your answer is the best one for you. – Ed Morton Aug 19 '13 at 19:10