I need to process many txt files (16 million lines for each file) using awk. I have to read, for example, ten files:
File # 1:
en sample_1 200
en.n sample_2 10
en sample_3 10
File No. 2:
en sample_1 10
en sample_3 67
File No. 3:
en sample_1 1
en.n sample_2 10
en sample_4 20
...
I would like to have this conclusion:
source name f1 f2 f3 sum (f1, f2, f3)
en sample_1 200 10 1 211
en.n sample_2 10 0 10 20
en sample_3 10 67 0 77
en sample_4 0 0 20 20
Here is my first version of the code:
#! /bin/bash
clear
BASEPATH=<path_to_file>
YEAR="2014"
RES_FOLDER="processed"
FINAL_RES="2014_06_01"
mkdir $RES_FOLDER
awk 'NF>0{a[$1" "$2]=a[$1" "$2]" "$3}END{for(i in a){print i a[i]}}' $BASEPATH/$YEAR/* > $RES_FOLDER/$FINAL_RES
And here is my conclusion:
en sample_1 200 10 1
en.n sample_2 10 10
en sample_3 10 67
en sample_4 20
I got a little confused about how to put a null column where no occurrence was found, and how to get the sum of the whole value. I know I have to use this:
{tot[$1" "$2]+=$3} END{for (key in tot) print key, tot[key]}
Hope someone helps. Thanks.
******** EDITED ********
I try to achieve my result in a different way. I create a bash script like this, it produces a sorted file with all my keys, it is very huge, about 62 million records, I cut this file into pieces and pass each part to my awk script.
BASH:
clear
FILENAME=<result>
BASEPATH=<base_path>
mkdir processed/slice
cat $BASEPATH/dataset/* | cut -d' ' -f1,2 > $BASEPATH/processed/aggr
sort -u -k2 $BASEPATH/processed/aggr > $BASEPATH/processed/sorted
split -d -l 1000000 processed/sorted processed/slice/slice-
echo $(date "+START PROCESSING DATE: %d/%m/%y - TIME: %H:%M:%S")
for filename in processed/slice/*; do
awk -v filename="$filename" -f algorithm.awk dataset/* >> processed/$FILENAME
done
echo $(date "+END PROCESSING DATE: %d/%m/%y - TIME: %H:%M:%S")
rm $BASEPATH/processed/aggr
rm $BASEPATH/processed/sorted
rm -rf $BASEPATH/processed/slice
AWK:
BEGIN{
while(getline < filename){
key=$1" "$2;
sources[key];
for(i=1;i<11;i++){
keys[key"-"i] = "0";
}
}
close(filename);
}
{
if(FNR==1){
ARGIND++;
}
key=$1" "$2;
keys[key"-"ARGIND] = $3
}END{
for (s in sources) {
sum = 0
printf "%s", s
for (j=1;j<11;j++) {
printf "%s%s", OFS, keys[s"-"j]
sum += keys[s"-"j]
}
print " "sum
}
}
awk , , dataset/*, .
, awk- (10 16.000.000 ).
, RAM (30 ) . - ? .