Thursday, September 1, 2011

Using awk to add elements of colum

Awk is a great tool to do manipulations on the data thats more or less structured. I had  a file that had logs from a simulation. I was trying to parse a log from Axi transaction logger and get the bandwidth numbers. For read bandwidth I had to search for ADDR_RD and the required data is in column 22 and column 19. I was planning to write the script in perl, but then remembered awk and wanted to give it a try. I found the script to be much simpler and classy. Here is the script. I am sure this would have taken me atleast 10 lines to write in perl.

/ADDR_RD/ {rd_bw+=$22*2^$19}
/ADDR_WR/ {wr_bw+=$22*2^$19}
END {print "ReadBW =" rd_bw ", WriteBW =" wr_bw}

Lets say we save this file in rd_wr_bw.awk. To use the script type:
awk -f rd_wr_bw.awk <filename to search>

Very simple and elegant. Love it!