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

      

+3


source to share


4 answers


Using perl from the command line,

perl -ne'
  print if /(Solaris|linux|unix|vms|win|proxy|terminal|unixware)/ && ++$s{$1}<=2;
' /etc/hosts

      



Output

192.9.200.12 Solaris1
192.9.200.13 Solaris2
192.9.200.17 linux1
192.9.200.18 linux2

      

+9


source


by awk



awk '/Solaris|linux|unix|vms|win|proxy|terminal|unixware/{a=$2;sub(/[0-9]*$/,"",a); if (++b[a]<=2) print}' /etc/hosts

      

+2


source


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

      

+2


source


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.

+1


source







All Articles