Lokaps
November 5, 2013, 9:23am
1
Hi, I need help with the awk command.
I have a folder with aprox 500 files each one with two columns and I want to print in a new file, the average of column 1 and average of column 2 and the name of each file.
Input files are:
File-1:
100 99
20 99
50 99
50 99
File-2:
200 85
50 85
100 85
Output file should contain:
namefile-1 55 99
namefile-2 116 85
namefile-3 avcol1 avcol2
...
I know how to do the average of column 1 for each file but I don't know how to do the rest
This is what I use:
(ls -r | while read filename; do awk '{sum+=$1} END {print sum/NR >> "newfile.tsv"}' $filename ; done)
Any ideas?
Thanks
[user@host ~]$ ls -l file*
-rw-r--r-- 1 user group 25 Nov 5 19:59 file1
-rw-r--r-- 1 user group 20 Nov 5 19:59 file2
[user@host ~]$ cat test.sh
#! /bin/bash
for f in file*
do
s1=0
s2=0
c=0
while read c1 c2
do
s1=$(( s1 + c1 ))
s2=$(( s2 + c2 ))
(( c++ ))
done < $f
echo "Name: $f --> $(( s1 / c )) $(( s2 / c ))"
done
[user@host ~]$ ./test.sh
Name: file1 --> 55 99
Name: file2 --> 116 85
[user@host ~]$
RudiC
November 5, 2013, 9:33am
3
Please use code tags as required by forum rules!
Try
awk 'FNR==1 && fn {print fn, sum1/cnt, sum2/cnt; cnt=sum1=sum2=0}
END {print fn, sum1/cnt, sum2/cnt}
{sum1+=$1;sum2+=$2;cnt++;fn=FILENAME}
' file1 file2
file1 55 99
file2 116.667 85
ls | while read file
do
printf "%s" "$file"
awk '{for (i=1;i<=NF;i++) {a+=$i; c++}} END {for (i=1;i in a;i++) printf " %.f",a/c}' "$file"
echo ""
done > ../newfile
NB put newfile to another directory to ensure that it is not considered by the ls
.