Skip to content

Instantly share code, notes, and snippets.

@somera
Forked from joshisa/URL Parsing
Created August 7, 2022 22:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save somera/162d8d08c2236f17c3aaea2f96730170 to your computer and use it in GitHub Desktop.
Save somera/162d8d08c2236f17c3aaea2f96730170 to your computer and use it in GitHub Desktop.
Parsing of URLs using bash sh scripting
#!/bin/bash
# Referenced and tweaked from http://stackoverflow.com/questions/6174220/parse-url-in-shell-script#6174447
proto="$(echo $1 | grep :// | sed -e's,^\(.*://\).*,\1,g')"
# remove the protocol
url="$(echo ${1/$proto/})"
# extract the user (if any)
userpass="$(echo $url | grep @ | cut -d@ -f1)"
pass="$(echo $userpass | grep : | cut -d: -f2)"
if [ -n "$pass" ]; then
user="$(echo $userpass | grep : | cut -d: -f1)"
else
user=$userpass
fi
# extract the host
host="$(echo ${url/$user@/} | cut -d/ -f1)"
# by request - try to extract the port
port="$(echo $host | sed -e 's,^.*:,:,g' -e 's,.*:\([0-9]*\).*,\1,g' -e 's,[^0-9],,g')"
# extract the path (if any)
path="$(echo $url | grep / | cut -d/ -f2-)"
echo "url: $url"
echo " proto: $proto"
echo " user: $user"
echo " pass: $pass"
echo " host: $host"
echo " port: $port"
echo " path: $path"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment