Sitemap
Mohit Arora

Mohit Arora

AWK Magic !!!

2 min readDec 27, 2018

If you are wondering what i am talking about. Please give a drum roll to the unix command AWK that is really powerful and I am going to show you why using an example. I am not being spender but once in a while like to calculate how much i am spending and on what.

So here is a snippet of my lavish lifestyle in csv (comma separated value) format.

Press enter or click to view image in full size

If you have guessed it as bank statement , you are right .

So now without further ado, lets dive in . As you can see there is some account info followed by transactions. We are only interested in later. How do we do it . We can summon AWK and ask for only lines that has as in this case 8 fields which form a transaction .

awk ‘NF==8 {print}’ FS=, DATA3.csv

So awk has essentially two parts one for putting conditions on what to process and what operation. NF==8 means process only those rows which has eight fields. The operation is print itself . Plus you will have to tell awk what field separator is being used .FS=, takes care of it . And voila we have filtered transactions

Press enter or click to view image in full size

Now you may want to be picky and see only information like how much did my wife spend on groceries at her favorite Krish mini mart. AWK to the rescue again

awk ‘NF==8 && /KRISH/ {print}’ FS=, DATA3.csv

You see what i did there I inserted a search pattern /KRISH/ that did the job for me.

Press enter or click to view image in full size

Now you must be pondering what if only i could calculate my groceries bill at KRISH. Well worry not .

awk ‘NF==8 && /KRISH/ { tot += $3; print} END {print “TOTAL : “ tot}’ FS=, DATA3.csv

Get Mohit Arora’s stories in your inbox

Join Medium for free to get updates from this writer.

Here we are adding the money spent from third field in a variable tot +=$3. And later using it to print the total expenses. Neat , isn’t it.

Press enter or click to view image in full size

--

--