Divide values in one column by the total number of lines in the file

Viewed 82

I have several data files in this format:

orange 25 high
red 23 low
blue 20 low
green 10 high

I would like to divide column 2 by the total number of lines in the file.
I've tried this:

awk '{$2=$2/NR}1'

but the output divides the first row by 1, the second by 2 etc. I want each row divided by the total number of lines in the file.

2 Answers

Get the number of lines first, and pass that to awk.

lines=$(wc -l < filename)
awk -v "lines=$lines" '{ $2 /= lines }1' filename

I would use GNU AWK and harness fact that NR is total number of rows inside END. Let file.txt content be

orange 25 high
red 23 low
blue 20 low
green 10 high

then

awk '{arr[NR]=$2}END{for(i=1;i<=NR;i+=1){print arr[i]/NR}}' file.txt

output

6.25
5.75
5
2.5

Explanation: During processing line I store value from 2nd column ($2) in associative array arr using current line number (NR) as key. After this done I use for loop to process arr keeping order. As I noted NR inside END is total number of rows. Note: this solution assumes you have enough memory to keep whole 2nd column in it.

(tested in gawk 4.2.1)

Related