1

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?

4
  • I am using a bash shell to execute this, so the option given about will not work... Commented Feb 25, 2014 at 13:08
  • so the option for command line will not work Commented Feb 25, 2014 at 13:11
  • Also if there are 3 lines maching, I would like to get only the first line number. Commented Feb 25, 2014 at 13:14
  • Update your question with a proper explanation instead of commenting here in the comments. Commented Feb 25, 2014 at 13:33

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

0

Or you can pass variable like this, after code:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.