RSS Subscription
Linux Howtos & Tutorials

Enter your email:

Delivered by


NOTE:New tutorials are from LinuxCareer.com

Poll

Do you own or wish to have iPhone?
 


Linux eBooks FREE Download
A guide to programming Linux kernel modules
Introduction to Linux - A Hands on Guide
A Newbie's Getting Started Guide to Linux

Linux from Scratch - Create Your Own Linux System - Free eBook

Linux: The Hacking Solution (v.3.0)

SQLite 3 with PHP Essential Training – Free Video Training Tutorials

This guide will introduce you to the world of GNU/Linux

The GNU/Linux Advanced Administration

A Complete Beginner's Manual for Ubuntu 10.04 (Lucid Lynx)

Advanced Bash-Scripting Guide

Set up, maintain, and secure a small office email server

Partner Linux Sites:
How-To.LinuxCareer.com
Jobs.LinuxCareer.com
TuxMachines
Monsterb
LinuxBloggers
AdamsInfo
LinuxScrew
All For Linux

Calculate column average using bash shell

Question:

Is there a way to calculate a average of a single column stored in a text file? For example my file contains:

$ cat file.txt
line1 4.5
line2 6

how do I get 5.25 ?

Answer:

One way to do this is to use combination of bash for loop, cut, echo and bc commands. Execute the code below, assuming that file.txt is in your current working directory:

 

$ count=0; total=0; for i in $( awk '{ print $2; }' file.txt );\
do total=$(echo $total+$i | bc ); \
((count++)); done; echo "scale=2; $total / $count" | bc
5.25

and here is a shell script version of the above command so we can see what is happening in more detail:

#!/bin/bash

count=0;
total=0; 

for i in $( awk '{ print $2; }' file.txt )
   do 
     total=$(echo $total+$i | bc )
     ((count++))
   done
echo "scale=2; $total / $count" | bc

For each line in file.txt we extract a second column with awk ( $i ). Then we use echo and bc command to add all numbers $i to get a total $total. The script also stores a number of loops $count. The last line uses echo and bc commands to calculate average with two decimal points.

awk only method:

You can also try use awk command:

$ awk '{ total += $2; count++ } END { print total/count }' file.txt 
5.25

Linux questions and answers

 

Share this linux post:

Submit Calculate column average using bash shell in Delicious Submit Calculate column average using bash shell in Digg Submit Calculate column average using bash shell in FaceBook Submit Calculate column average using bash shell in Google Bookmarks Submit Calculate column average using bash shell in Stumbleupon Submit Calculate column average using bash shell in Technorati Submit Calculate column average using bash shell in Twitter
 
Comments for this page are closed !!!
Please visit our new Linux Forum for additional help or discussion.


Linux eBooks FREE Download