简体   繁体   中英

Awk - using an array with multiple files

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM