I'm using AWK
for multiline matching with patterns.
Example:
awk '/"ip": /,/"id": /'
I would like to pass an argument to AWK when I know the ip
, so that it would return the lines that include the specified IP. Example:
awk '/"ip": "$IP"/,/"id": /'
What would be a way to do it?
I have tried:
awk '/"ip": "$IP"/,/"id": /'
awk '/"ip": "${IP}"/,/"id": /'
awk "/\"ip\": \"$IP\"/,/\"id'\": /"
I was wondering how to use this approach with patterns:
var="hello"; awk -v a="$var"
Thanks.
ANSWER
- accepted and can be found below.
Additional details for anyone interested on how to make the matching more precise (using the variable + a string pattern). Take note that you can't wrap the variable you are using in the pattern with double quotes, it will not work even if the quotes are escapted:
cat l.txt | awk '$0 ~ "\"ip\": \"103.6.181.43", $0 ~ "\"id\": \""' ===> works cat l.txt | awk -v ipvar=103.6.181.43 '$0 ~ ipvar, $0 ~ "\"id\": \""' ===> works cat l.txt | awk -v ipvar=103.6.181.43 '$0 ~ "\"ip\": \"ipvar", $0 ~ "\"id\": \""' ===> does not work cat l.txt | awk -v ipvar=103.6.181.43 '$0 ~ "\"ip\": \""ipvar, $0 ~ "\"id\": \""' ===> works
Finally, you can wrap / surround the parameter used in qoutes. Compare:
awk -v ipvar=103.6.181.43 '$0 ~ "\"ip\": \"ipvar\"", $0 ~ "\"id\": \""' ===> will not work
awk -v ipvar=103.6.181.43 '$0 ~ "\"ip\": \""ipvar"\"", $0 ~ "\"id\": \""' ===> will work and is equivalent.