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:
xxxxxxxxxx
1
echo 'https://dirask.com:8080/about' | awk 'match($0,/^[a-z]+:\/\/(www\.)?([^?#/]+)/,g){print g[2]}'
In this solution, we use match()
function that lets to use regular expression with groups support.
xxxxxxxxxx
1
2
3
echo 'https://dirask.com:8080/about' | awk 'match($0,/^[a-z]+:\/\/(www\.)?([^?#/]+)/,g){print g[2]}'
4
echo 'https://www.dirask.com:8080/about' | awk 'match($0,/^[a-z]+:\/\/(www\.)?([^?#/]+)/,g){print g[2]}'
Output:
xxxxxxxxxx
1
dirask.com:8080
2
dirask.com:8080
xxxxxxxxxx
1
2
3
function get_origin() {
4
echo "$1" | awk 'match($0,/^[a-z]+:\/\/(www\.)?([^?#/]+)/,g){print g[2]}'
5
}
6
7
8
# Usage example 1:
9
10
get_origin 'https://dirask.com:8080/about'
11
get_origin 'https://www.dirask.com:8080/about'
12
13
14
# Usage example 2:
15
16
origin_1="$(get_origin 'https://dirask.com:8080/about')"
17
origin_2="$(get_origin 'https://www.dirask.com:8080/about')"
18
19
echo $origin_1
20
echo $origin_2
Output:
xxxxxxxxxx
1
dirask.com:8080
2
dirask.com:8080
3
4
dirask.com:8080
5
dirask.com:8080