1

I to calculate the average over each row but without including the first value. Example:

1   12 13 14 15 16 17 18   
2   21 22 23 24 25 26 27 28 29     
... --------

I want the output likes like

1  15   
2  25   
....
1
3

A perl one:

perl -MList::Util=sum -ane 'printf "%s %s\n", shift @F, sum(@F)/(@F?@F:1)' file
1 15
2 25
2
  • this print only the regular numbers and desnot consider irregular ones like 1.532 also it stops with empty rows (row contains only the first value) because the division by zero – Mohsen El-Tahawy Aug 7 '15 at 10:27
  • @MohsenEl-Tahawy: Fixed it! You should include those information in your question. – cuonglm Aug 7 '15 at 10:30
1

You can try with awk:

awk '{ s = 0; for (i = 2; i <= NF; i++) s += $i; print $1, (NF > 1) ? s / (NF - 1) : 0; }' file

result:

1 15
2 25
2
  • very nice but I have some rows empty i.e. contain only the first value and the commend is stopped when it find empty row because the division by zero – Mohsen El-Tahawy Aug 7 '15 at 10:19
  • @MohsenEl-Tahawy, answer edited. – taliezin Aug 7 '15 at 10:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.