I am trying to print occurrences of a field in a .csv file only using an awk command. For example in a file test.csv like so:
layla;rebel;TAT
han_solo;rebel;TAT
darth_vader;empire;DKS
yoda;rebel;TAT
with the command:
cat test.csv | ./how_many_are_we.sh dks
I wish to have the following output:
1
Here is my code in how_many_are_we.sh (which is working but case-sensitive):
#! /bin/bash
awk -F ";" -v location=$1 'BEGIN {count=0;} { if ($3 == location) count+=1} END {print count}'
I tried adding IGNORECASE=1 in different places but I can't seem to find the right way to make it work.
Excuse my bad wording, and thank you for the help.
You could change the case of entered value and for 3rd field to lower case and then compare their values to make sure however they are entered comparison shouldn't be affected.
#!/bin/bash
awk -F ";" -v location="$1" 'BEGIN {location=tolower(location);count=0;} { if (tolower($3) == location) count+=1} END {print count+0}' Input_file
OR As per Glenn sir's comments use shell trick to make it lowercase in variable itself.
#!/bin/bash
awk -v location="${1,,}" 'BEGIN{FS=";"} (tolower($3) == location){count+=1} END{print count+0}' Input_file
OR more awksh way change awk command to following(above is OP's command fix this is to make it awksh style)
awk -v location="$1" 'BEGIN{location=tolower(location);FS=";"} (tolower($3) == location){count+=1} END{print count+0}'
NOTE: For using IGNORECASE=1, you should mention it either in BEGIN section like BEGIN{IGNORECASE=1} OR like an awk variable -v IGNORECASE="1".
Also on a side note, OP's shebang is having spaces between #! and /bin/bash which shouldn't be the case so I had fixed that too here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With