简体   繁体   中英

Searching pattern in awk from variable

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
  1. Problem is: when I use variable $search_pattern - awk show output only: / 5

  2. 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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM