Often you may want to use Bash to extract a domain name from a URL.
You can use the following syntax to do so:
echo $my_url | awk -F[/:] '{print $4}'
This particular example will extract the domain name from the URL saved in the variable named my_url.
Here is how this syntax works:
- echo $my_url: Display entire string from $my_url variable.
- awk -F[/:]: Use forward slash and colon as field separators.
- print $4: Print the fourth field, which will be the domain name only.
The following example shows how to use this syntax in practice.
Example: How to Extract Domain Name from URL in Bash
Suppose that we create a variable named my_url in Bash that contains the following URL:
- https://collectingwisdom.com/bash-tutorials/
And suppose that we would like to extract only the domain name from the URL to get:
- collectingwisdom.com
We can use the following syntax to do so:
my_url="https://collectingwisdom.com/bash-tutorials/"
echo $my_url | awk -F[/:] '{print $4}'
The following screenshot shows how to use this syntax in practice:

Notice that we’re able to extract the following text:
- collectingwisdom.com
This represents only the domain name of the URL.
We could also use the following syntax to save this domain name to a new variable named my_domain:
my_url="https://collectingwisdom.com/bash-tutorials/"
my_domain=$(echo $my_url | awk -F[/:] '{print $4}')
echo $my_domain
The following screenshot shows how to use this syntax in practice:

Notice that when we use the echo statement to view the my_domain variable we can see that it contains only the domain name of the URL.
Related Tutorials
The following tutorials explain how to perform other common tasks in Bash:
Bash: How to Extract Text Between Two Strings
Bash: How to Extract String from Brackets
Bash: How to Replace Multiple Characters in String
