issue with nawk while using variable assignment

 
#ifconfig -a | nawk '/1.1.1.1/{print}'
inet 1.1.1.1 netmask xxxxxxxxx broadcast 0.0.0.0

If i assign the ip to a variable and search for the variable nothing gets printed!!

 
# ifconfig -a | nawk -v ip=1.1.1.1 '/ip/{print}'

I am not able to understand why this is happening!

You cannot use a variable name like that in a regex. Try:

ifconfig -a | nawk -v ip=1.1.1.1  ' match( $0, ip )'

Thanks agama.. it works..

My requirement here would be to search for 1.1.1.1 and get the value of mac-address from the next line.

 
bge0: flags=123243432<UP,BROADCAST,RUNNING,MULTICAST,IPv4,FIXEDMTU> mtu 1500 index 2
        inet 1.1.1.1 netmask xxxxxxxx broadcast 0.0.0.0
        ether 0:11:11:23:w2:62

can you please tell me how to get this?

Have a go with this:

ifconfig -a |awk -v ip=1.1.1.1  ' match( $0, ip ) {getline; print $2; exit}'

It works. Thanks. i am trying to understand this oneliner. does it mean the match function searches for the match and holds something like pointer to the line thats matched and whatever processing is done would start from the matched line onwards ?

this should work too..

ifconfig -a | awk -v ip=1.1.1.1  '$0 ~ ip'

I'll add some comments to explain:

ifconfig -a |awk -v ip=1.1.1.1  ' 
match( $0, ip ) {      # if the ip address is on this line
     getline;             # get the next line from the input file
     print $2;            # print the second field 
     exit;                 # stop processing input
}'

Remember that awk reads each line of the input file (output from ifconfig in this case) and applys the condition to the line. In this case the condition is the match command which returns true when the desired string is somewhere in the input line.

It could also be written like this, which I think is a bit easier to understand, but less clear as a one liner:

ifconfig -a |awk -v ip=1.1.1.1  ' 
{
  if( match( $0, ip ) )
  {
     getline;
     print $2;
     exit;
  }
}'

Hope this helps.