How to use grep to match domain names?

10,018

In order to use non-greedy regexes with grep you will need to use the -P option and the -o option outputs only the matching portion. You will also need to use lookarounds so that part of the match is not included in the output.

grep -Po '.*?//\K.*?(?=/)'

Example:

$ echo 'hxxp://subdomain.url3.com/somepage.php' | grep -Po '.*?//\K.*?(?=/)'
subdomain.url3.com
Share:
10,018

Related videos on Youtube

김승재
Author by

김승재

Updated on September 17, 2022

Comments

  • 김승재
    김승재 over 1 year

    I have a list of urls like:

    hxxp://url.com/subpage.html
    hxxp://www.url2.com/index.php
    hxxp://subdomain.url3.com/somepage.php
    ...
    

    How can I use grep to match the domain names only?

    All the urls have a / after the domain. And there are a lot of tlds, not sure how many, the list is quite big.

  • Karl Bielefeldt
    Karl Bielefeldt about 13 years
    That won't work for http://url.com/directory/page.html