I'm using Bash on Ubuntu and my issue is the following:
I have a large text file with a header and where the delimiter is #|#
.
I'm trying to use AWK to get some information on this file. Right now I would like to compute the sum of column 2 group by values of column 1, with this expression:
awk 'BEGIN { FS="\\#\\|\\#" }{arr[$1]+=$2} END {for (i in arr) {print i,arr[i]}}' myfile.txt
There are two issues with the output I get:
First, if let's say that column 1 takes two unique values value1 and value2, then AWK forms not 2 but 3 groups: value1, value2 and also name_column1.
As if it didn't understand the first row of the file was a header...
The second issue is that my output is:
value1 0 value2 0 name_column1 0
So we know the last line of the output is unexpected (as mentionned previously) so let's focus on the two first ones. Here, both sums are null but I know that at least one of them should be strictly greater than 0 because the command
awk 'BEGIN { FS="\\#\\|\\#" }{sum1+=2;}END{print sum1;}' myfile.txt
gives me
251597850
.
So either there is something wrong with my last command (regular sum), either with the previous one (sum+group by).
Does someone know how to fix this?
EDIT: My file text looks like something like that:
Column1#|#Column2#|#Column3
0300#|#0.00#|#0000
where 0300 is the value1
previously mentioned (it is not a number but a category).
EDIT2:
awk 'BEGIN { FS="\\#\\|\\#" }{sum1+=2;}END{print sum1;}' myfile.txt
gives me 2*(number of rows in file), which is obviously not what I want, so the command should be:
awk 'BEGIN { FS="\\#\\|\\#" }{sum1+=$2;}END{print sum1;}' myfile.txt
EDIT3 :
Turns out both my commands were wrong because of the separator. The right command for the group by therefore is:
awk 'BEGIN { FS="#[|]#" } FNR>1 {arr[$1]+=$2} END { for (i in arr) print i,arr[i] }' file.txt
sum1+=$2
isntead ofsum1+=2
.FNR > 1
.