문제

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

도움이 되었습니까?

해결책

/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

다른 팁

Or you can have variable behind awk

awk '$0 ~ var {print $1}' var="ip" file
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top