user1651888
user1651888

Reputation: 463

awk command with search string variable

Configuration.xml has "mysearchstring" at position (line) 23.

If I use the following statement, it returns me line 23

awk '/"mysearchstring"/{print NR}' Configuration.xml 

But if I use an assigned variable, it returns me nothing

str="mySearchString";awk '/$str/{print NR}' Configuration.xml

Can someone tell me what is incorrect in the second statement?

Upvotes: 1

Views: 477

Answers (3)

Jotne
Jotne

Reputation: 41460

Or you can pass variable like this, after code:

awk '$0~s {print NR}' s="$str" file

Upvotes: 0

Arkku
Arkku

Reputation: 42159

You can use the command-line option -v to pass variables to awk:

awk -v searchstr="$str" '$0 ~ searchstr { print NR }'

Upvotes: 1

fedorqui
fedorqui

Reputation: 290465

You need to pass the variable to awk with -v and then use the ~ comparison:

awk -v myvar="$str" '$0 ~ myvar {print NR}' Configuration.xml

Example

$ cat a
hello
how
are 
you

$ awk '/e/ {print NR}' a <---- hardcoded
1
3

$ awk -v myvar="e" '$0~myvar {print NR}' a <---- through variable
1
3

Upvotes: 2

Related Questions