EN
Bash - get path name from given URL
0
points
In this article, we would like to show you how to get path name from given URL in Bash.
Quick solution:
echo 'https://dirask.com/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/about' | awk 'match($0,/^[a-z]+:\/\/(www\.)?[^:?#/]+(\/[^?#]*)?/,g){print g[2]}'
echo 'https://www.dirask.com/about' | awk 'match($0,/^[a-z]+:\/\/(www\.)?[^:?#/]+(\/[^?#]*)?/,g){print g[2]}'
Output:
/about
/about
Reusable example
#!/bin/bash
function get_path() {
echo "$1" | awk 'match($0,/^[a-z]+:\/\/(www\.)?[^:?#/]+(\/[^?#]*)?/,g){print g[2]}'
}
# Usage example 1:
get_path 'https://dirask.com/about'
get_path 'https://www.dirask.com/about'
# Usage example 2:
path_1="$(get_path 'https://dirask.com/about')"
path_2="$(get_path 'https://www.dirask.com/about')"
echo $path_1
echo $path_2
Output:
/about
/about
/about
/about