Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace substring in string

i have just tried to one of my first bash scripts, i need to find a substring(after the ? part) in a url and replaced with the replace_string,

  #!/bin/bash

url="https://example.com/tfzzr?uhg"
#       123456 ...


first= echo `expr index "$url" ?`
last= expr length $url
replace_string="abc"



part_to_be_replace = echo ${url:($first+1):$last}//dont know how to use variable here

substring(url,part_to_be_replace,replace_string)

It does not work, i was able to find only the first accurance of ?, and the length of the string

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Does this help?

url="https://example.com/tfzzr?uhg"
replace_string="abc"

echo "${url}"
https://example.com/tfzzr?uhg

echo "${url//\?*/${replace_string}}"
https://example.com/tfzzrabc

# If you still want the "?"
echo "${url//\?*/\?${replace_string}}"
https://example.com/tfzzr?abc

See https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html for further details.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading