Search code examples
awkaveragemeanone-liner

Bash one liner for calculating the average of a specific row of numbers in bash


I just began learning bash.

Trying to figure out how to convert a two-liner into a one liner using bash.

The First Line of code...

  1. searches the first column of the input.txt for the word - KEYWORD.

  2. captures every number in this KEYWORD row from column2 until the last column.

  3. dumps all these numbers into the values.txt file placing each number on a new line.

The second line of code calculates average value for all the numbers in the first column of values txt the prints out the this value.

awk '{if($1=="KEYWORD") for(i=2;i<=NF;i++) print $i}' input.txt > values.txt
awk 'BEGIN{sum=0; counter=0}{sum+=$1; counter+=1}END{print sum/counter}' values.txt 

How do I create a one liner from this?


Solution

  • Something like

    awk '
      BEGIN { count = sum = 0 }
      $1 == "KEYWORD" {
        for (n = 2; n <= NF; n++) sum += $n
        count += NF - 1
      }
      END { print sum/count }' input.txt
    

    Just keep track of the sum and total count of numbers in the first (and only) pass through the file and then average them at the end instead of printing a value for each matching line.