0

Today I have a script that inside of it has a query that does a SELECT of the column name and the count of it. It can list more than 50+ different lines.

Ex.

BOOK 12
SHELF 2
DESK 3

Outline code:

[query] | while read unk_mtype_volume ; do

    echo "$unk_mtype_volume"

done

I need to SUM every row number, to have a total.

0

2 Answers 2

2

This is a simple job for awk, no expensive iteration over the lines of the file/input needed. Just add up the second fields, and finally print the value:

awk '{sum+=$2} END{print sum}' file.txt

If the input is coming from STDIN:

... | awk '{sum+=$2} END{print sum}'

Example:

% cat file.txt
BOOK 12
SHELF 2
DESK 3

% awk '{sum+=$2} END{print sum}' file.txt
17
Sign up to request clarification or add additional context in comments.

Comments

0

You can (and I would) use awk for the job — as shown by heemayl in their answer. You can also do it in pure Bash:

sum=0
while read location number
do
    sum=$(($sum + $number))
done
echo "Total: $sum"

Note that this is fragile if any of the 'locations' consists of more than one word. You can code around that more easily in awk than Bash.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.