1

I have the following code

var="ip"

awk '/$var/{
print $1
}' file

But it doesn't work, I believe I cant use $var inside the awk, and I tried
-v var="$var" as well but it didnt work either

1
  • What shell language are you using? Different ones may have different rules about how and when a variable ($var) gets expanded within a string of some sort. Commented May 9, 2014 at 14:25

2 Answers 2

3

/pattern/ does not work with a variable, because it is looking for the literal text pattern instead of the variable.

Instead, to get this functionality you have to use $0 ~ var:

awk -v var="ip" '$0 ~ var {print $1}' file

Example

$ cat a
123.456.789 is my ip
this is another thing

$ awk -v var="ip" '$0 ~ var {print $1}' a
123.456.789
Sign up to request clarification or add additional context in comments.

Comments

0

Or you can have variable behind awk

awk '$0 ~ var {print $1}' var="ip" file

1 Comment

...but don't do that unless you need to change the variable's initial value between file opens as it makes it harder to add code later that, for example, does something with the variable in the BEGIN section or loops through ARGV expecting to find just file names. It's also just plain counter-intuitive to have the code that inits a variable appear AFTER the code that uses the variable.

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.