user2616677
user2616677

Reputation:

Having SUM issues with a bash script

I'm trying to write a script to pull the integers out of 4 files that store temperature readings from 4 industrial freezers, this is a hobby script it generates the general readouts I wanted, however when I try to generate a SUM of the temperature readings I get the following printout into the file and my goal is to print the end SUM only not the individual numbers printed out in a vertical format Any help would be greatly appreciated;here's my code

grep -o "[0.00-9.99]" "/location/$value-1.txt" | awk '{ SUM += $1; print $1} END { print SUM }' >> "/location/$value-1.txt"

here is what I am getting in return

    Morningtemp:17.28
Noontemp:17.01
Lowtemp:17.00 Hightemp:18.72
1
7
.
2
8
1
7
.
0
1
1
7
.
0
0
1
8
.
7
2
53

It does generate the SUM I don't need the already listed numbers, just the SUM total

Upvotes: 0

Views: 63

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753485

The regex in grep -o "[0.00-9.99]" "/location/$value-1.txt" is equivalent to [0-9.], but you're probably looking for numbers in the range 0.00 to 9.99. For that, you need a different regex:

grep -o "[0-9]\.[0-9][0-9]" "/location/$value-1.txt"

That looks for a digit, a dot, and two more digits. It was almost tempting to use [.] in place of \.; it would also work. A plain . would not; that would select entries such as 0X87.

Note that the pattern shown ([0-9]\.[0-9][0-9]) will match 192.16.24.231 twice (2.16 and 4.23). If that's not what you want, you have to be a lot more precise. OTOH, it may not matter in the slightest for the actual data you have. If you'd want it to match 192.16 and 24.231 (or .24 and .231), you have to refine your regex.

Your command structure:

grep … filename | awk '…' >> filename

is living dangerously. In the example, it is 'OK' (but there's a huge grimace on my face as I type 'OK') because the awk script doesn't write anything to the file until grep has read it all. But change the >> to > and you have an empty input, or have awk write material before the grep is complete and suddenly it gets very tricky to determine what happens (it depends, in part, on what awk writes to the end of the file).

Upvotes: 1

James Brown
James Brown

Reputation: 37394

Why not stick with AWK completely? Code:

$ cat > summer.awk 
{
    while(match($0,/[0-9]+\.[0-9]+/))    # while matches on record
    {
        sum+=substr($0, RSTART, RLENGTH) # extract matches and sum them
        $0=substr($0, RSTART + RLENGTH)  # reset to start after previous match
        count++                          # count matches
    }
} 
END {
    print sum"/"count"="sum/count        # print stuff

Data:

$ cat > data.txt
    Morningtemp:17.28
Noontemp:17.01
Lowtemp:17.00 Hightemp:18.72

Run:

$ awk -f summer.awk file
70.01/4=17.5025

It might work in the winter too.

Upvotes: 1

Related Questions