-3

I have a repetition starting at row zzz in a text file.

zzz ***Wed Aug 16 06:00:30 UTC 2017
MemTotal:       195702024 kB
MemFree:         1323524 kB
..
Cached:         58020288 kB
..other rows
zzz ***Wed Aug 16 06:01:00 UTC 2017
MemTotal:       195702024 kB
MemFree:         1379588 kB
..other rows
Cached:         58001952 kB
..other rows

I want to sum up the values of MemFree: and Cached: for each repetition. There are 3 columns on such lines. KB being the third column.

For eg:

MemFree:         1323524 kB + Cached:         58020288 kB = 59343812 
MemFree:         1379588 kB + Cached:         58001952 kB = 59381540

Want an output like:

Total Available Memory = 59343812
Total Available Memory = 59381540
...
...
0

I’m not clear what “row zzz” has to do with the question.  Are there other occurrences of “MemFree:” and “Cached:” before row zzz that you want ignored?  But here is a simple solution to capture the value from the second column of a “MemFree:” line, save it, and add it to the value from the next “Cached:” line:

awk '
    $1 == "MemFree:" { free = $2 }
    $1 == "Cached:"  { print "Total Available Memory =", free+$2 }
    '

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.