Getting IP Address using awk

July 19, 2009

Useful for..

  • Scripts
  • Checking IP Address Often

Command

lenny-dhabba:/home/sameer# ifconfig eth1 | awk '/dr:/{gsub(/.*:/,"",$2);print$2}'
169.254.167.101

lenny-dhabba:/home/sameer# ifconfig | awk '/dr:/{gsub(/.*:/,"",$2);print$2}'
192.168.1.8

169.254.167.101

127.0.0.1

Tools

  • ifconfig command
  • awk

Explanation

The command used for finding IP Address is ifconfig, it produces lot of output, what we need is the IP Address of any interface or of all interfaces, for this, we send the output of ifconfig to another command line tool called awk. Awk’s job is to remove the unnecessary things from ifconfig’s output, for this we tell awk using a language it understands. From this language awk interprets it as:

  1. Find a line containing the string “dr” . As we know the second line in ifconfig output contains the IP Address.
  2. Next get the string near to inet addr
  3. Finally print that string

. Hence we get the desired output.

Disadvantages

  • Prints unnecessary new line characters in between
  • There are better ways to print the characters using perl

References