Home > Net >  Replace substring in string
Replace substring in string

Time:12-01

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

CodePudding user response:

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.

CodePudding user response:

Use parameter expansion:

#! /bin/bash

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

new=${url%\?*}?$replace_string
echo "$new"
  • ${url%\?*} removes the pattern (i.e. ? and anything following it) from $url. ? needs to be quoted, otherwise it would match a single character in the pattern. Double the percent sign to remove the longest possible substring, i.e. starting from the first ?.
  • Related