Sopalajo de Arrierez
Sopalajo de Arrierez

Reputation: 3850

Variable based AWK partly string match (if column/word partly matches)

This question comes from this other.

Case scenario for my Linux shell script:

$ cat test.txt
C1    C2    C3
1     a     snow
2     b     snowman
snow     c     sowman

Searching for lines with third field containing "snow" works OK:

$ awk '$3 ~/snow/' test.txt
1     a     snow
2     b     snowman

But I need to do it by using variables:

$ word="snow"

$ echo $word
snow

$ awk -v variable="snow" '$3 ~/variable/' test.txt

$ awk -v variable="$word" '$3 ~/variable/' test.txt

$

As can be seen, there are no results.

How could I perform AWK search variable-based?

Upvotes: 1

Views: 1198

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133428

You should change $3 ~/variable/ TO $3 ~ variable since a /../ contains regexp not variables. So in your case it will try to search "a string" named variable NOT "a variable" named variable.

Upvotes: 2

Related Questions