1

I'm new to shell scripting, and I need to compute an average file1, and then the average of the result and a number in file2, so far i came up with this, but it doesn't print anything.

awk '{if ($FILENAME == "spring") array[$1]=($2+$3+$4+$5+$6+$7+$8)/7; if($FILENAME == "fall") array[$1]=(array[$1]+$2)/2 }  END { for (var in array) print var,array[var]}' ./spring ./fall

Any way to solve this problem?

1
  • 2
    To get a decent answer you need to post both files and the output you expect. Commented Mar 29, 2013 at 16:21

2 Answers 2

1

How about awk '{s+=$1}ENDFILE{print FILENAME,s/FNR;s=0}' RS=" " file1 file2:

$ cat file1
1 2 3 4 5 6 7 8

$ cat file2
1 2

$ awk '{s+=$1}ENDFILE{print FILENAME,s/FNR;s=0}' RS=" " file1 file2
file1 4.5
file2 1.5
Sign up to request clarification or add additional context in comments.

Comments

1

There are no sigils in awk. Try dropping the $:

awk 'FILENAME ~ /spring/ { array[$1]=($2+$3+$4+$5+$6+$7+$8)/7 }
   FILENAME ~ /fall/ { array[$1]=(array[$1]+$2)/2 }  
   END { for (var in array) print var,array[var]}' ./spring ./fall

In short, FILENAME is the name of the file currently being processed, but $FILENAME is equivalent to $0 when FILENAME starts with a letter.

2 Comments

FILENAME is including the path, so FILENAME == "./spring".
@WalterA Good catch. Not sure how an answer can go this long with such an error! Editing to be slightly more robust

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.