Reputation: 6783
I'd like to write a Bash script that reports a sum. I'm starting with 20 text files that have the text "LOC: 54" somewhere in them (the "54" could be any integer). So here are the results of searching for this line with grep:
# grep LOC *
ceil.c: * LOC: 38
count_newlines.c: * LOC: 28
even.c: * LOC: 35
every_product.c: * LOC: 48
expand_factors.c: * LOC: 54
factor.c: * LOC: 41
fibonacci.c: * LOC: 49
get_element.c: * LOC: 37
is_composite.c: * LOC: 43
isprime.c: * LOC: 36
largest.c: * LOC: 37
max_product.c: * LOC: 68
mult_list.c: * LOC: 38
nlist.c: * LOC: 37
palindrome.c: * LOC: 72
prime_factors.c: * LOC: 57
remove_dups.c: * LOC: 50
select_products.c: * LOC: 36
square_list.c: * LOC: 31
sum_list.c: * LOC: 38
What could I do to pull just the numerical information together to produce a single number, the sum of the above numbers? I believe in the above example it would be 873.
Upvotes: 1
Views: 2591
Reputation: 6911
This is a pure bash script. Does not work with floating point numbers though
#!/bin/bash
shopt -s nullglob
declare -i sum=0
for file in file*
do
if [ -f "$file" ];then
while read -r line
do
case "$line" in
*"LOC: "* )
[[ $line =~ "LOC: ([0-9]+)" ]]
((sum+=${BASH_REMATCH[1]}))
;;
esac
done < "$file"
fi
done
echo "Sum: $sum"
Upvotes: 1
Reputation: 246744
Just an exercise, not the best solution
set -- $(awk '/LOC:/ {print $NF}' filename)
IFS='+'
answer=$( echo "$*" | bc )
Upvotes: 0
Reputation: 17188
Pure Bash. The following script sum.sh does it:
declare sum=0
while read -a line ; do
(( sum += ${line[@]: -1} )) # sum up last elements
done < <(grep --exclude=*.sh LOC *) # exclude script files
echo -e "sum = $sum"
Upvotes: 0
Reputation: 5249
This awk
script will add those lines that contain LOC:
, and end with a number:
grep LOC * | awk 'BEGIN { FS= "LOC: "; sum = 0 } NF==2 && /[0-9]+$/ { sum+=$2 } END { print sum }'
Upvotes: 0