LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (http://www.linuxquestions.org/questions/linux-general-1/)
-   -   Separating Fields from Output - cut command (http://www.linuxquestions.org/questions/linux-general-1/separating-fields-from-output-cut-command-829036/)

Hi_This_is_Dev 08-28-2010 02:47 PM

Separating Fields from Output - cut command
 
Hi,


I want to display only the IP Address Value 10.0.2.15 from the output of:

Code:

ifconfig eth0 | grep "inet addr"
as given below:

Code:

[root@localhost ~]# ifconfig eth0 | grep "inet addr"
          inet addr:10.0.2.15  Bcast:10.0.2.255  Mask:255.255.255.0
[root@localhost ~]# ifconfig eth0 | grep "inet addr" | cut -d: -f2
10.0.2.15  Bcast
[root@localhost ~]#

but it is displaying the text "Bcast" as well.

The main problem here is that the first value and the second field / column name have no delimiter to separate them.



Okay, this one is working:

Code:

[root@localhost ~]# ifconfig eth0 | grep "inet addr" | cut -d: -f2 | cut -d" " -f1
10.0.2.15
[root@localhost ~]#

But can we have a better approach?

druuna 08-28-2010 03:05 PM

Hi,

ifconfig eth0 | awk 'BEGIN{ FS="[ : ]"} /inet addr/ { print $13 }'

That is a tab (ctrl-v + tab) followed by a colon and a space between the brackets (the blue part).

The cut command can only have 1 specific delimiter, awk can have multiple. You can also use awk to "grep" for a pattern.

Hope this helps.

forrestt 08-28-2010 03:10 PM

This seems a little more elegant, but it could probably be improved as well.

Code:

ifconfig | sed -ne 's/.*inet addr:\(.*\)  B.*/\1/p'
HTH

Forrest

p.s. was saying more elegant than the OP, not druuna. Got a phone call during post, and didn't refresh before submitting to se that post.

colucix 08-28-2010 03:23 PM

Another way in awk (portable to non-GNU awk versions):
Code:

/sbin/ifconfig eth0 | awk '/inet/{sub(/addr:/,"",$2); print $2}'


All times are GMT -5. The time now is 07:02 AM.