Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing subdomain with bash

Tags:

bash

sed

awk

Suppose i have a variable called $subdomainthat contain test.google.com .How can i strip the subdomain to get google.comand store it in a variable called $maindomain.

like image 237
user2650277 Avatar asked Dec 04 '25 13:12

user2650277


2 Answers

One subdomain

maindomain=${subdomain#*.}  

with more subdomains

maindomain=$(sed 's/.*\.\(.*\..*\)/\1/' <<< $subdomain)

Remove URI if there is one

maindomain=$(sed 's/.*\.\(.*\..*\)/\1/' <<< ${subdomain%/*})
maindomain=${subdomain#[[:alpha:]]*.}

will remove "test." or any other similar prefix, before the first point.

Better answer, as we can have multiple subsubdomains:

maindomain=$(expr match "$subdomain" '.*\.\(.*\..*\)')

It keeps only the trailing xxxxxx.xxx part of a domain.

like image 29
jaybee Avatar answered Dec 07 '25 06:12

jaybee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!