-1

I am trying to get the first 3 lines of ip address/ifconfig from some VMs - some of them are running on Ubuntu, some of them on CentOS.

For example:

eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 9001
        inet 172.31.106.100  netmask 255.255.240.0  broadcast 172.31.111.255
        inet6 fe80::10c5:1dff:fec0:803e  prefixlen 64  scopeid 0x20<link>
        ether 12:c5:1d:c0:80:3e  txqueuelen 1000  (Ethernet)
        RX packets 7483  bytes 7706844 (7.3 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 2998  bytes 470781 (459.7 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 12100  bytes 3865475 (3.6 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 12100  bytes 3865475 (3.6 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

From this block of lines, I would need to get just the following part:

eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 9001
        inet 172.31.106.100  netmask 255.255.240.0  broadcast 172.31.111.255
        inet6 fe80::10c5:1dff:fec0:803e  prefixlen 64  scopeid 0x20<link>

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>

The same should apply for an ip address command. Is any way to achieve this using a Linux command?

Many thanks,

Romain

Romain
  • 171
  • 1
  • 3
  • 15
  • redirect output to file and read first 3 lines (there is no ipconfig in Linux by the way to my knowledge) – Drako Aug 01 '18 at 09:07
  • @Drako: You're right, I edited my question. It was related to ip address, not ipconfig. For the solution, I would prefer CWLiu's one. – Romain Aug 01 '18 at 09:34
  • Please avoid *"Give me the codez"* questions. Instead show the script you are working on and state where the problem is. Also see [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/q/261592/608639) – jww Aug 01 '18 at 19:39

1 Answers1

0

You may use sed to do that,

ifconfig | sed -En '/^[^[:space:]]/,+2p; /^[[:space:]]*$/p'

Brief explanation,

  • The pipeline result would be processed by sed
  • /^[^[:space:]]/,+2p: search and print the line which doesn't start with blank, and also print the following 2 lines
  • /^[[:space:]]*$/p: search and print the blank line
CWLiu
  • 3,913
  • 1
  • 10
  • 14