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
You could look it up in any online awk reference:
Or without tail:
Using awk with bc to have arbitrary long results (credits to
Jouni K.
):I have a utility script which simply adds up all columns. It's usually easy enough to grab the one you want from the one-line output. As a bonus, some SI-suffixes are recognized.
Example with custom field separator:
If you have specific, multiple columns you want to sum, you can use:
which will work if you want to sum columns 1–5.
You could start by running the data through
cut
- which would at least trim the columns down.You should then be able to pipe that into
grep
, stripping-out non-numerics.Then ... well, then I'm not sure. It might be possible to pipe that to
bc
. If not, it could certainly be handed to a shell script to add each item.If you used
tr
to change the newlines (\n
) to spaces (), and piped that through xargs into your script that loops until there are no more inputs, adding each one, you may have an answer.
So, something akin to the following:
I may have the
cut
flags slightly wrong - butman
is your friend :)I would try to construct a calculation string and feed it to bc as follows:
ipcs -mb | grep -w '^m ' | sed 's/^.*\s//' | xargs | tr ' ' + | bc
Looks like this is slightly longer than the awk solution, but for everyone who can't read (and understand) the odd awk code this may be easier to grasp... :-)
If bc is not installed you can use double parentheses in step 5 above to calculate the result:
echo $(( $(ipcs -mb | grep -w '^m ' | sed 's/^.*\s//' | xargs | tr ' ' +) ))
orSUM=$(( $(ipcs -mb | grep -w '^m ' | sed 's/^.*\s//' | xargs | tr ' ' +) ))
or(( SUM=$(ipcs -mb | grep -w '^m ' | sed 's/^.*\s//' | xargs | tr ' ' +) ))
The spacing after and before the double parentheses is optional.