We already writtn one excellent string manipulation post for shell. This post is in response to the code which I seen in my office for greping IP address from ifconfig command. The command is..

	ifconfig eth0 | grep 'inet addr' | cut -d: -f 2 | awk '{print $1}'

Above command explanation:
Grep command will filter ifconfig command output to list only ip address line.
Cut command then cuts out that line to print only ip address and a word Bcast
Then awk command just prints first column of the output.

This will get the IP address of the network interface. I don't blame or point out the flaw in this command. But I want to show the beauty of awk command which is good at text parsing and even sub strings as well.

In awk there is a search function which we can accomplish with // as shown below

	ifconfig eth0 | awk '/inet addr/ {print}'

Output:

	          inet addr:192.168.1.135  Bcast:192.168.1.255  Mask:255.255.255.0
	Now how to get IP address part from this line? Use below command
	ifconfig eth0 | awk '/inet addr/{print $2}'
	Output:
addr:192.168.1.135

But how can I remove that addr: from the output? There is an builtin function in AWK which is useful to print sub strings. The syntax for this is as follows.

	awk '{print substr(column-number,start-point,end-point)}'

Note: End-point is an optional argument.
So now you want to print just 192.168.1.135, to do that we have to find from what character you want to print from above output. As my requirement is just IP address, I want my string to be displayed from 6th character to end.

	$ ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'
	Output:
192.168.1.135


Suppose if you just want to print only first three characters then use below command.

	$ ifconfig eth0 | awk '/inet addr/{print substr($2,6,3)}'
	Output:
192

See the beauty of awk, we eliminate two commands(grep and cut) from the actual command. Hope you enjoyed reading, keep visiting linuxnix.com.

The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.