EN
Bash - get location origin from given URL
0
points
In this article, we would like to show you how to get location origin from given URL in Bash.
Quick solution:
echo 'https://dirask.com:8080/about' | awk 'match($0,/^[a-z]+:\/\/(www\.)?([^?#/]+)/,g){print g[2]}'
Practical example
In this solution, we use match() function that lets to use regular expression with groups support.
#!/bin/bash
echo 'https://dirask.com:8080/about' | awk 'match($0,/^[a-z]+:\/\/(www\.)?([^?#/]+)/,g){print g[2]}'
echo 'https://www.dirask.com:8080/about' | awk 'match($0,/^[a-z]+:\/\/(www\.)?([^?#/]+)/,g){print g[2]}'
Output:
dirask.com:8080
dirask.com:8080
Reusable example
#!/bin/bash
function get_origin() {
echo "$1" | awk 'match($0,/^[a-z]+:\/\/(www\.)?([^?#/]+)/,g){print g[2]}'
}
# Usage example 1:
get_origin 'https://dirask.com:8080/about'
get_origin 'https://www.dirask.com:8080/about'
# Usage example 2:
origin_1="$(get_origin 'https://dirask.com:8080/about')"
origin_2="$(get_origin 'https://www.dirask.com:8080/about')"
echo $origin_1
echo $origin_2
Output:
dirask.com:8080
dirask.com:8080
dirask.com:8080
dirask.com:8080