0

I compute the row average of the following data set however I have trouble setting the correct format for $0 so as to produce the file-output presented below. I currently have:

awk '{T=0; for (i=1;i<=NF;i++) T+=$i; T/=NF; printf "??f 6.3f\n",$0,T}' fileinput > fileoutput

file input

1   2   3   4
3   3   8   8
5   4   13  12
7   5   18  16
9   6   23  20
11  7   28  24
13  8   33  28
15  9   38  32
17  10  43  36
19  11  48  40
21  12  53  44
23  13  58  48
25  14  63  52

desire file output

1   2   3   4   2.5
3   3   8   8   5.5
5   4   13  12  8.5
7   5   18  16  11.5
9   6   23  20  14.5
11  7   28  24  17.5
13  8   33  28  20.5
15  9   38  32  23.5
17  10  43  36  26.5
19  11  48  40  29.5
21  12  53  44  32.5
23  13  58  48  35.5
25  14  63  52  38.5
1
  • what about "%s %.1f\n?
    – pLumo
    Jun 25, 2020 at 15:04

2 Answers 2

2

A slightly alternate awk

awk -F'\t' 'BEGIN {OFS=FS}{s=$1; for (i=2;i<=NF;i++) s+=$i; $(NF+1)=sprintf("%.1f", s/NF)}1' file

Maintain the input and output file format the same by setting OFS=FS (I used a tab in your file)

No need to zero s, just set s=$1 and iterate over the rest for (i=2;...

Then if you sprintf your sum to $(NF+1) you can just default print $0 with OFS (that's the 1 at the end).

1       2       3       4       2.5
3       3       8       8       5.5
5       4       13      12      8.5
7       5       18      16      11.5
9       6       23      20      14.5
11      7       28      24      17.5
13      8       33      28      20.5
15      9       38      32      23.5
17      10      43      36      26.5
19      11      48      40      29.5
21      12      53      44      32.5
23      13      58      48      35.5
25      14      63      52      38.5

Though you could also

awk '{s=$1; for (i=2;i<=NF;i++) s+=$i; $(NF+1)=sprintf("%.1f", s/NF)}1' file | column -t
1   2   3   4   2.5
3   3   8   8   5.5
5   4   13  12  8.5
7   5   18  16  11.5
9   6   23  20  14.5
11  7   28  24  17.5
13  8   33  28  20.5
15  9   38  32  23.5
17  10  43  36  26.5
19  11  48  40  29.5
21  12  53  44  32.5
23  13  58  48  35.5
25  14  63  52  38.5
1

The formatting string for awk printf() follows the same conventions as for C printf(), so in principle

awk '{T=0; for (i=1;i<=NF;i++) T+=$i; T/=NF; printf "%s%s%6.3f\n",$0,OFS,T}' fileinput > fileoutput

should work.

The minimal change necessary to your current attempt is to state

printf "%s %6.3f\n",$0,T

but I propose to separate $0 and T using the actual value of the output field separator OFS just in case it isn't a single space, but a TAB or something else.

2
  • sorry it's fine I had some weird spaces in my input file after fixing them it was absolutely fine! thanks!! Jun 25, 2020 at 15:11
  • Ok, you had me worried there for a moment ;)
    – AdminBee
    Jun 25, 2020 at 15:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .