Farhad Sakhaei Farhad Sakhaei - 6 months ago 30
Perl Question

Regular Expression, Extract main domains from a list of domains and subdomains

This is a sample list containing of sub domains and domains,

sub1.domain.com
sub2.domains2.com
domain3.com
sub5.domain.ext
subof.subdomain.domainx.ex2


I want to just extract main domain names from this list using regular expression
Thank you

Answer

You can use grep with PCRE:

grep -Po '\.?\K[^.]+\.[^.]+$' file.txt

Example:

$ cat file.txt
sub1.domain.com
sub2.domains2.com
domain3.com
sub5.domain.ext
subof.subdomain.domainx.ex2

$ grep -Po '\.?\K[^.]+\.[^.]+$' file.txt
domain.com
domains2.com
domain3.com
domain.ext
domainx.ex2
Comments