How to match only the first two hosts from a host file
with following egrep command I am getting hosts from / etc / hosts file in following example
egrep "Solaris|linux|unix|vms|win|proxy|terminal|unixware" /etc/hosts
192.9.200.12 Solaris1
192.9.200.13 Solaris2
192.9.200.14 Solaris3
192.9.200.15 Solaris4
192.9.200.16 Solaris5
192.9.200.17 linux1
192.9.200.18 linux2
192.9.200.19 linux3
192.9.200.20 linux4
192.9.200.21 linux5
i want to add awk or sed or perl one liner command that will only print the first two hosts of the match like below:
egrep "Solaris|linux|unix|vms|win|proxy|terminal|unixware" | ...... /etc/hosts
192.9.200.12 Solaris1
192.9.200.13 Solaris2
192.9.200.17 linux1
192.9.200.18 linux2
source to share
Another awk way
awk '
match($0,/Solaris|linux|unix|vms|win|proxy|terminal|unixware/,a)&&++b[a[0]]<=2
' file
Explanation
Matches the list of names and stores in a variable a
(this does not include the number after).
Then adds another array b
named a[0]
and checks if it is at least 2 The default awk action is printed
VOILA
192.9.200.12 Solaris1
192.9.200.13 Solaris2
192.9.200.17 linux1
192.9.200.18 linux2
awk '{t=$2; sub(/[0-9]+$/,"",t)} /Solaris|linux|unix|vms|win|proxy|terminal|unixware/ && ++cnt[t] <= 2' /etc/hosts | sort
Logic:
variable t
will contain the last modified field (for example: Solaris1 => Solaris, Solaris2 => Solaris, linux1 => linux, linux3 => linux, etc.), if the current line matches the pattern and less than 2 matches are found, print the line .. At the end sort
if required.
source to share