AloneInTheDark
AloneInTheDark

Reputation: 938

How to find patterns across multiple lines in Linux?

i'm trying to get some specific lines of this command:

ifconfig

here is the output of the command:

eth0      Link encap:Ethernet  HWaddr 00:10:E0:3F:6F:BC  
          inet addr:10.71.1.30  Bcast:10.71.1.255  Mask:255.255.255.0
          inet6 addr: fe80::210:e0ff:fe3f:6fbc/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:3059275068 errors:0 dropped:1378 overruns:0 frame:0
          TX packets:2094779962 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:6566542892239 (5.9 TiB)  TX bytes:202791652910 (188.8 GiB)

eth1      Link encap:Ethernet  HWaddr 00:10:E0:3F:6F:BD  
          UP BROADCAST RUNNING SLAVE MULTICAST  MTU:1500  Metric:1
          RX packets:1417584931 errors:0 dropped:32908 overruns:0 frame:0
          TX packets:1284691038 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:2256566826674 (2.0 TiB)  TX bytes:182643225952 (170.0 GiB)

I just want lines that contains "Link" and "bytes" words, for example:

eth0      Link encap:Ethernet  HWaddr 00:10:E0:3F:6F:BC 
RX bytes:6566542892239 (5.9 TiB)  TX bytes:202791652910 (188.8 GiB)
eth1      Link encap:Ethernet  HWaddr 00:10:E0:3F:6F:BD
RX bytes:2256566826674 (2.0 TiB)  TX bytes:182643225952 (170.0 GiB)

Upvotes: 0

Views: 116

Answers (4)

Cameron Kerr
Cameron Kerr

Reputation: 1875

Here's a couple of useful patterns that most people I've met don't seem to know about. The first is particularly relevant to your problem.

grep -e is your best new-found friend

ifconfig | grep -e Link -e bytes

You can do a similar thing with sed, which has an additional bonus of also printing out the first line (which might contain a heading). In this example, I'm printing out the heading line and any lines contain LISTEN or 'bar' (The second expression is just there to reinforce the fact that you're not limited to one.) Here, the 1p is addressing the first line, (origin-1), with the operation to 'p'rint

lsof -Pni | sed -n -e 1p -e '/LISTEN/p' -e '/bar/p'

Upvotes: 0

fedorqui
fedorqui

Reputation: 289745

Te best approach must be to use grep to filter the lines. For example, use:

ifconfig | egrep " Link|bytes"

Note I added a space before Link to avoid matching the line ending with Scope:Link.

You can also use:

ifconfig | awk '/ Link/ || /bytes/'

or

ifconfig | grep " Link\|bytes"

Upvotes: 2

sat
sat

Reputation: 14949

Of course grep is the best tool for this. But, there are some other ways are available to do the same. That is,

ifconfig | sed -n '/Link \|bytes/p'

and

ifconfig | awk '/Link |bytes/'

Upvotes: 1

Vijay
Vijay

Reputation: 67231

ifcofig|perl -lne 'print if(/Link/||/bytes/)'

Upvotes: 0

Related Questions