I'm sure there is a quick and easy way to calculate the sum of a column of values on Unix systems (using something like awk
or xargs
perhaps), but writing a shell script to parse the rows line by line is the only thing that comes to mind at the moment.
For example, what's the simplest way to modify the command below to compute and display the total for the SEGSZ column (70300)?
ipcs -mb | head -6
IPC status from /dev/kmem as of Mon Nov 17 08:58:17 2008
T ID KEY MODE OWNER GROUP SEGSZ
Shared Memory:
m 0 0x411c322e --rw-rw-rw- root root 348
m 1 0x4e0c0002 --rw-rw-rw- root root 61760
m 2 0x412013f5 --rw-rw-rw- root root 8192
Thanks for the Python one-liner above!. It helped me to easy check the used space on my drive. Here is a mixed shell / Python one-liner, that do this - counts used space on the device /dev/sda in megabytes. It took me some time, before I found it out, so, maybe someone finds this useful too.
or more Python / less shell:
Thanks again!
Python Solution
Most Linux distros have Python.
If you want to process stdin as part of a pipline, use
If you want to assume that there's always 3 header lines:
One-liner:
To sum values in a column you can use GNU datamash. Since the first four lines do not contain values you want to sum up, we remove them with
tail +4
.The
-W
option sets the field delimiter to (possibly multiple) whitespaces.I know this question is somewhat dated, but I can't see "my" answer here, so I decided to post nonetheless. I'd go with a combination of
+
sign)ipcs
doesn't give an output on my system, so I'll just demo it withdf
:I know doing this particular calculation on my system doesn't really make sense, but it shows the concept.
All of the pieces of this solution have been shown in the other answers, but never in that combination.