1

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.

5 Answers 5

5
awk -F: '/LOC/ {sum += $3;} END {print sum;}' InputFileName
Sign up to request clarification or add additional context in comments.

3 Comments

How does this work? It's not looking for the specific text "LOC"
Ah, I see: grep LOC * | awk -F: '{sum += $3;} END {print sum;}'
No need for a separate grep. Just add a /LOC/ in the sum statement. Updated the post. You can make it even more specific if needed i.e. / * LOC/
1

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"

Comments

0

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 }'

Comments

0

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"

1 Comment

you have grep :). not really pure bash
0

Just an exercise, not the best solution

set -- $(awk '/LOC:/ {print $NF}' filename)
IFS='+'
answer=$( echo "$*" | bc )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.