0

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 ?

1
  • Please let me know if my answer was helpful.
    – Chris Rees
    Dec 10, 2016 at 9:34

2 Answers 2

1

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?

0

I believe you can solve your issue with this code:

#!/bin/bash

hostname=test.example.com01 #or example.com01 or foo.test.example.com01
echo $hostname
reg0='^.*\.\([a-z0-9_-]*\.[a-z_-]*\)[0-9]*$'
reg1='^\([a-z0-9_-]*\.[a-z_-]*\)[0-9]*$'
domain=`expr "$hostname" : "$reg0" '|' "$hostname" : "$reg1"`
echo $domain

Let me explain: expr STRING:REGEX will do the same as expr match. The | in the middle means: if "$hostname" : "$reg0" is null try "$hostname" : "$reg1". Regexes implicitly start with ^ as documentation of coreutils said and the string returned is the one inside \( and \).

Remember that * is greedy and try to match everything as long as it can.

Said this, the program starts with reg0 that match all the third level, fourth level etc domains... but can't match the example.com01 due to the first dot. If $hostname is not a third level domain or more $reg0 return null and now comes reg1 that match example.com01 style domains.

I have tryed the program and everything seems to work in the way you want.

You must log in to answer this question.

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