0

I have an URL in the format like https://foo.bar.whoo.dum.io, for which I like to replace the foo string with something else. Of course, the foo part is unknown and can be anything.

I tried with a simple regex like (.+?)\.(.+), but it seems that regex in Bash is always greedy (or?).

My best attempt is to split the string by . and then join it back with the first part left out, but I was wondering, whether there is a more intuitive, different solution.

Thank you

1

3 Answers 3

4

There are a lot of ways of getting the desired output.

If you're sure the url will always start with https://, we can use parameter expansion to remove everything before the first . and then add the replacement you need:

input="https://foo.bar.whoo.dum.io"

echo "https://new.${input#*.}"

Will output

https://new.bar.whoo.dum.io

Try it online!

Sign up to request clarification or add additional context in comments.

1 Comment

Nice one. People tend to forget about parameter expansion in Bash and go for external binaries like sed, cut, and awk based solutions.
3

You can use sed:

url='https://foo.bar.whoo.dum.io'
url=$(sed 's,\(.*://\)[^/.]*,\1new_value,' <<< "$url")

Here, the sed command means:

  • \(.*://\) - Capturing group 1: any text and then ://
  • [^/.]* - zero or more chars other than / and .
  • \1new_value - replaces the match with the Group 1 and new_value is appended to this group value.

See the online demo:

url='https://foo.bar.whoo.dum.io'
sed 's,\(.*://\)[^/.]*,\1new_value,' <<< "$url"
# => https://new_value.bar.whoo.dum.io

Comments

1

1st solution: Using Parameter expansion capability of bash here, adding this solution. Where newValue is variable with new value which you want to have in your url.

url='https://foo.bar.whoo.dum.io'
newValue="newValue"
echo "${url%//*}//$newValue.${url#*.}"


2nd solution: With your shown samples, please try following sed code here. Where variable url has your shown sample url value in it.

echo "$url" | sed 's/:\/\/[^.]*/:\/\/new_value/'

Explanation: Simple explanation would be, printing shell variable named url value by echo command and sending it as a standard input to sed command. Then in sed command using its capability of substitution here. Where substituting :// just before1st occurrence of . with ://new_value as per requirement.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.