Results 1 to 4 of 4

Thread: Bash Script to read and compute several lines

  1. #1
    Join Date
    Oct 2008
    Location
    Sweden
    Beans
    85
    Distro
    Ubuntu 13.04 Raring Ringtail

    Bash Script to read and compute several lines

    So, I have a file which get a new number added to it every day. And I want to read the 7 last numbers from this file, add them together and then divide by 7 to get an average.

    Code:
    week=$(tail -n 7 data.txt)
    
            while read score
            average=$($average + $score)
            done < $week
    
    average2=$($average / 7)
    echo $average2
    Well, It fails, and google unfortunatly didn't turn up much :/

    I get the sense there is a more elegant way of doing this than using loads of variables.

  2. #2
    Join Date
    Apr 2012
    Beans
    7,064

    Re: Bash Script to read and compute several lines

    How about

    Code:
    sum=0
    while read val
      do ((sum+=$val))
    done < <(tail -7 data.txt)
    echo $((sum/7))
    Remember that the shell itself only does integer division - if you want a floating point average you will need to pipe it to bc, I think, e.g.

    Code:
    echo "scale = 2; $sum/7" | bc
    [FYI you should probably count the number of lines that it actually reads and divide by that - rather than assuming tail will return 7 lines]

  3. #3
    Join Date
    Feb 2009
    Location
    Dallas, TX
    Beans
    7,737
    Distro
    Ubuntu 16.04 Xenial Xerus

    Re: Bash Script to read and compute several lines

    Hi Valpskott.

    If you are not committed to do it purely on bash, here's an alternately solution that uses awk:
    Code:
    tail -n 7 data.txt | awk 'BEGIN{sum=0} {sum+=$1} END{print sum/7}'
    Regards.

  4. #4
    Join Date
    Oct 2008
    Location
    Sweden
    Beans
    85
    Distro
    Ubuntu 13.04 Raring Ringtail

    Re: Bash Script to read and compute several lines

    Thank you both of you for your suggestions!

    I went the "non awk" route, even though the awk thing worked, I'm yet to familiarize myself with awk and how it's syntax goes, and I already needed to tweak something.

    Marking as solved

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •