Search code examples
shellawkgrepcut

How to get the paragraph contain the key words in shell scripts?


I want to get the whole paragraph that contain the key words.

For example, the following is the output of "ifconfig -a"

bond0     Link encap:Ethernet  HWaddr 00:11:3F:C1:47:98  
          inet6 addr: fe80::211:3fff:fec1:4798/64 Scope:Link
          UP BROADCAST RUNNING MASTER MULTICAST  MTU:1500  Metric:1
          RX packets:1881856 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1059020 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:2618747813 (2.4 GiB)  TX bytes:182058226 (173.6 MiB)

bond0:oam Link encap:Ethernet  HWaddr 00:11:3F:C1:47:98  
          inet addr:135.2.156.97  Bcast:135.2.156.111  Mask:255.255.255.240
          UP BROADCAST RUNNING MASTER MULTICAST  MTU:1500  Metric:1

bond0:oamA Link encap:Ethernet  HWaddr 00:11:3F:C1:47:98  
          inet addr:135.2.156.103  Bcast:135.2.156.111  Mask:255.255.255.240
          UP BROADCAST RUNNING MASTER MULTICAST  MTU:1500  Metric:1

And I want to extract the paragraph in bold. That is, the paragraph contain the key words "bond0:oamA" I know if I use grep, only the line

bond0:oamA Link encap:Ethernet  HWaddr 00:11:3F:C1:47:98 

will be got. But I want to extract the whole paragraph contain the key words.

Is there a method to get this paragraph?

Thanks a lot!


Solution

  • Try this command:

    ifconfig -a | awk -vRS='' '$1~/bond0:oamA/'
    

    When RS is null, awk parse file as multi-line-record.