Separating Fields from Output - cut command

Whether you are using Linux on the desktop or as a server, it's still good that you're using Linux. Linux related questions go here.

Moderator: General Moderators

Post Reply
devarishi
Forum Contributor
Posts: 101
Joined: Fri Feb 05, 2010 7:15 pm

Separating Fields from Output - cut command

Post 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?
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: Separating Fields from Output - cut command

Post 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
Doug G
Forum Contributor
Posts: 282
Joined: Sun Sep 09, 2007 6:27 pm

Re: Separating Fields from Output - cut command

Post by Doug G »

Thanks for the useful grep snip :)
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: Separating Fields from Output - cut command

Post 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.
Post Reply