Question

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

Was it helpful?

Solution

/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

OTHER TIPS

Or you can have variable behind awk

awk '$0 ~ var {print $1}' var="ip" file
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top