Reputation: 561
I have data input data:
AAA
AAA
AA
BBB
BB
I would like to do something like this:
#!/bin/bash
search_pattern=AA
awk '-v search='$search_pattern' /search/ {count ++}END {print count, "/", NR} ' input
Desire output is:
1 / 5
Problem is: when I use variable $search_pattern
- awk show output only: / 5
How to "tell" awk to search only AA (not AAA) = force PATTERN to match only whole words
Thank you for any help.
EDIT:
Would be possible to add condition, if does not match any string, print 0 / 5
Upvotes: 1
Views: 1793
Reputation: 556
Ravinder's solution is correct. Just adding this as another way using pattern matching.
search_pattern=^AA$
awk -v search="$search_pattern" 'BEGIN{count=0} $0 ~ search {count++} END{print count, "/", NR}' input
^ = beginning of the line.
$ = end of the line.
So, AAA would not be counted.
Upvotes: 1
Reputation: 133428
Search will take other strings too which will have this string in them, so try following.
var="AA"
awk -v VAR="$var" '$0 == VAR{count++;} END{print count " / " NR}' Input_file
Or with your shown variable names etc.
search_pattern=AA
awk -v search="$search_pattern" '$0 == search {count++}END {print count, "/", NR}' Input_file
EDIT: OP added additional requirement of adding 0 to output if no matches found for string into Input_file, following may help in same.
awk -v search="$search_pattern" '$0 == search {count++}END {print count?count:0, "/", NR}' Input_file
Upvotes: 3