1

I'm making a script that will remove the http:// or https:// from a URL. So far I've got it to remove the http://, but I can't seem to figure out how to modify it so that it will remove either that they input. Here's the code so far:

domain=$1

inp="${domain//http:'//'}"

echo "$inp"

I'm needing code that would look something like this:

domain=$1

inp="${domain//http:'//'} OR ${domain//https:'//'}"

echo "$inp"

How would I go about doing this?

1

POSIX shell script:

inp="${domain#http*://}"

Test:

for domain in 'https://foo.bar/baz' 'http://foo.bar/baz' ; do \
    inp="${domain#http*://}" ; \
    echo "$inp" ; \
done

Output:

foo.bar/baz
foo.bar/baz
2

Besides running twice:

Using extended glob:

shopt -s extglob
v=${domain#http?(s)://}
printf "%s\n" "$v"

Using bash internal variable BASH_REMATCH:

Requiring protocol:

if [[ "$domain" =~ https?://(.*) ]]
then
    printf "%s\n" "${BASH_REMATCH[1]}"
else
    printf "Not valid input: '%s'\n" "$domain"
fi

Not requiring protocol:

[[ "$domain" =~ (https?://)?(.*) ]] && v="${BASH_REMATCH[2]}"
printf "%s\n" "$v"
1

Just do it twice:

inp="${domain//http:'//'}"
inp="${inp//https:'//'}"
  • Ah well I feel dumb and that works, thanks a ton! – Egrodo May 16 '16 at 15:48
  • @Egrodo If this answer solved your issue, please take a moment and accept it by clicking on the check mark to the left. That will mark the question as answered and is the way thanks are expressed on the Stack Exchange sites. – terdon May 16 '16 at 15:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.