Tuesday, November 16, 2021

[SOLVED] count how many times a word appears in a specific cloumn bash

Issue

this is a file that i have named people.txt

10001:Larry Simpson:65:NewYork:555666777
10002:Jonh Fin:91:Rome:333444555
10003:George Jas:86:Amsterdam:777888999
10004:Larry Simpson:65:NewYork:555666777
10005:Jonh Fin:91:Rome:333444555

I was trying to count how many people there was on a specific city that is given as argument of the script.

First thing i thought was:

grep "$1:" people.txt | wc -l

The ":" was because we can have a city named Amster and another named Amsterdam.

But then I realized that we can have people named Amsterdam, so I tried this to search in cities column:

k=$(awk -F ":" -v loc=$1 -v max=0 ' {if ($4==loc) max++; print max}' people.txt)
echo $k

But now the output is like 0 0 1 1 1 and how can I have just the last digit of this output? I also tried with cut but when doing -f we don´t know how long that output is.

Desired output is just 1

Regards


Solution

Assuming $1 is equal to "NewYork":

 awk -F: -v loc="$1" '$4==loc { cnt++ } END { print cnt}' people.txt

You need to use the END block to print the final count.



Answered By - Raman Sailopal