1

I'm having trouble writing a sed command do the following. I have a file that should only contain "valid" domain names. How I use with sed to remove any line that does not match an expression?

The following seems to match the lines I want to keep in the online tool I used, though I'm sure it could be written better.

^*.*[a-zA-Z0-9][a-zA-Z0-9-]+\.[a-zA-Z]{2,15}?$

The file

example.example.example.org
01.001.11.00.example.com
asdf-asdf-asdf-www.example.net
example
example.example.co.uk
(example)
example.photography
example.info
example/
example.
example</h1>
{example}
etc.

Expected output:

example.example.example.org
01.001.11.00.example.com
asdf-asdf-asdf-www.example.net
example.example.co.uk
example.photography
example.info

Thanks for the help.

1 Answer 1

0

I had to modify your regex to make it valid but this sed command prints only the lines that match:

$ sed -nr '/[.].*[a-zA-Z0-9][a-zA-Z0-9-]+([.][a-zA-Z]{2,15})?$/p' file
example.example.example.org
01.001.11.00.example.com
asdf-asdf-asdf-www.example.net
example.example.co.uk
example.photography
example.info

How it works

  • -n

    This tells sed not to print a line unless we explicitly ask it to.

  • -r

    This tells sed to use extended regular expressions.

  • /[.].*[a-zA-Z0-9][a-zA-Z0-9-]+([.][a-zA-Z]{2,15})?$/p

    /.../ selects lines that match the regex and /.../p tells sed to print the lines that match the regex.

Changes to the regex

Note that ^* is not a valid way to start a regex. ^ matches the beginning of a line and * would matchs zero or more of the preceding character but no preceding character is given. This could be made valid with the addition of a period as in ^.*. That matches a line that starts with anything. But, since that is not helpful here, I removed it.

Also, since it seems that you wanted to exclude lines that end with a period, I changed \.[a-zA-Z]{2,15}?$ to ([.][a-zA-Z]{2,15})?$.

For other people's attempts at making a regex to match domain names, see, for example, Domain name validation with RegEx or regex match main domain name.

1
  • 1
    That seems to do it, thank you for the help.
    – Mike
    Jul 16, 2015 at 23:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .