Page 1 of 1

Separating Fields from Output - cut command

Posted: Sat Aug 28, 2010 1:50 pm
by devarishi
Hi,


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

Code: Select all

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

Code: Select all

[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: Select all

[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?

Re: Separating Fields from Output - cut command

Posted: Fri Sep 03, 2010 5:57 pm
by McInfo

Code: Select all

ifconfig eth0 | grep -Po "(?<=inet addr:)([0-9\.]+)"
grep options:
  • -P, --perl-regexp interpret pattern as Perl regex
  • -o, --only-matching print only matching parts
regex:
  • (?<=) positive lookbehind assertion
  • inet addr: a literal string
  • ([0-9\.]+) one or more of digits or decimal points

Re: Separating Fields from Output - cut command

Posted: Fri Sep 03, 2010 6:38 pm
by Doug G
Thanks for the useful grep snip :)

Re: Separating Fields from Output - cut command

Posted: Fri Sep 03, 2010 7:22 pm
by McInfo
Doug G wrote:Thanks for the useful grep snip :)
:)

I recently wiped my hard drive and reinstalled Vista and Ubuntu 10.04, which got me in the mood for scouting the Linux forum.