XorOrNor
XorOrNor

Reputation: 8978

Bash expr error

I have a few text files with numbers (structure as below). I'd like to sum up every line form one file with ever line form other files (line1 from file1 + line1 from file2 etc.). I have written the bash script as following but this gives me the expr error.

function countHourly () {


for i in {1..24}
    do
        for file in $PLACE/*.dailycount.txt
            do
            SECBUFF=`head -n $i $file`
             VAL=`expr $VAL + $SECBUFF` ## <-- this cause expr error

        done
      echo line $i form all files counts: $VAL
done

}    

file structure *.dailycount.txt: 1 0 14 56 45 0 3 45 23 23 9 (every number in new line).

Upvotes: 0

Views: 150

Answers (3)

konsolebox
konsolebox

Reputation: 75568

This could help. With that variation you could check very input so that only numbers would be added for the sum, even if there are lines that invalid.

function countHourly {
    local NUMBERS TOTAL=0 I

    readarray -t NUMBERS < <(cat "$PLACE"/*.dailycount.txt)

    for I in "${NUMBERS[@]}"; do
        [[ $I =~ ^[[:digit:]]+$ ]] && (( TOTAL += I ))
    done

    echo "Total: $TOTAL"
}

Or

function countHourly {
    local NUMBERS TOTAL=0 I

    while read I; do
        [[ $I =~ ^[[:digit:]]+$ ]] && (( TOTAL += I ))
    done < <(cat "$PLACE"/*.dailycount.txt)

    echo "Total: $TOTAL"
}

Upvotes: 0

rici
rici

Reputation: 241901

Assuming your files each contain exactly 24 lines, you could solve this problem with a simple one-liner:

counthourly() {
  paste -d+ $PLACE/*.dailycount.txt | bc
}

Upvotes: 3

Joni
Joni

Reputation: 111349

The head -n NUMBER FILE command outputs the first NUMBER lines. This means that SECBUFF ends up being 1 0 on the second run of the loop, and something like expr 1 + 2 3 is not a valid expression so you get an error from expr.

You can use sed to pick only the nth line from a file, but I wonder if you shouldn't restructure the program somehow.

        SECBUFF=`sed -ne ${i}p $file`

Upvotes: 1

Related Questions