AWK substr function explained with examples
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...
Read More