Bash – Regular expression for second and third domain level with hyphens

bashregexregular expressionsshellshell-scripting

I have some smart script, that check name of server and get domain name. For example, i have name of server: example.ru01. I need to get: example.ru My scipt:

#!/bin/bash

hostname=example.com01
echo $hostname
reg0="\(\([a-z0-9_-]*\)\|\([a-z0-9_-]*\.[a-z_-]*\)\)"
domain=`expr match $hostname $reg0`
echo $domain

It is ok. in output i have:

example.com01
example.com

But, when i write domain of third level, i have output:

example.com.us01
example.com

So, i need another regular expression. I have written this:

reg0="\(\([a-z0-9_-]*\)\|\([a-z0-9_-]*\.[a-z0-9_-]*\.[a-z_-]*\)\)"

Output:

example.com.us01
example.com.us

It works. But, when i write domain of second level, i have output:

example.com01
example

So… Can i write a regular expression two both types of domain ?

Best Answer

This looks like a homework question.

How about using * with the parentheses?

subdomain\.(domain)*

Or, how about simply stripping the last digits?

(.*)[0-9][0-9]

You need to be more specific; do you need to validate the input?

Related Topic