Taking the average of two columns and printing it on a new column

Hi,

I have a space delimited text file that looks like the following:

Aa 100 200
Bb 300 100
Cc X 500
Dd 600 X

Basically, I want to take the average of columns 2 and 3 and print it in column 4. However if there is an X in either column 2 or 3, I want to print the non-X value. Therefore the output will look like this:

Aa 100 200 150
Bb 300 100 200
Cc X 500 500
Dd 600 X 600

How do I go about doing this? Thanks!

awk '/X/ { for(N=2; N<=NF; N++) if($N != "X") break } $4=$N; print; next } { $4=($3+$2)/2 } 1' inputfile

I get the following error msg when I try the code:

awk: /X/ { for(N=2; N<=NF; N++) if($N != "X") break } $4=$N; print; next } { $4=($3+$2)/2 } 1
awk: ^ syntax error
awk: each rule must have a pattern or an action part
awk: /X/ { for(N=2; N<=NF; N++) if($N != "X") break } $4=$N; print; next } { $4=($3+$2)/2 } 1
awk:

There is an extra "}" exists, try with above.

How would I go about altering the code if there are more than 2 files?

Depends what you want it to do with those files.

Sorry, I meant more than two columns so that the code would have to be altered to take the average of more than two columns ignoring the X's.

awk '{ T=0; C=0; for(N=1; N<=NF; N++) if($N != "X") { T+=$N; C++ } $(NF+1)=T/C } 1' input

Hmm, this code does not really achieve that. What I meant was that the code should take the average of the "non X" values in a single row and print it in the last column.

Sample input:

Aa 100 X X
Bb 100 200 300
Cc 100 200 X

Output:

Aa 100 X X 100
Bb 100 200 300 200
Cc 100 200 X 150

In what way does it not "achieve that"?

Sample input:

Aa 100 X X
Bb 100 200 300
Cc 100 200 X

Sample output

Aa 100 X X 50
Bb 100 200 300 150
Cc 100 200 X 100

I see the problem. Change N=1 to N=2 so it starts at the second field instead of the first.