awk to search similar strings and add their values

Hi,

I have a text file with the following content:

monday,20
tuesday,10
wednesday,29
monday,10
friday,12
wednesday,14
monday,15
thursday,34

i want the following output:

monday,45
tuesday,10
wednesday,43
friday,12
thursday,34

Please suggest a way to get this done.

Thanks,
Prashu

$ nawk -F, '{OFS=","}{a[$1]+=$2}END{for(i in a){print i, a}}' test.txt
wednesday,43
thursday,34
tuesday,10
monday,45
friday,12
1 Like

that worked fine.. could you kindly explain what "OFS" does and why that "END" is used and what is happening in all.. i'm actually new to scripting so please forgive my lack of knowledge..

Thanks,
Prashu

nawk -F, '{OFS=","}{a[$1]+=$2}END{for(i in a){print i, a}}' test.txt

OFS => Output Field Separator. This contains the character with which output fields would be separated. In this case, its defined as comma.
END => This block will be executed after all the lines in file 'test.txt' are processed.

1 Like