0

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

Inian
  • 80,270
  • 14
  • 142
  • 161
Andrewboy
  • 364
  • 5
  • 15

2 Answers2

2

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.

jared_mamrot
  • 22,354
  • 4
  • 21
  • 46
1

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 ?.
choroba
  • 231,213
  • 25
  • 204
  • 289
  • thank you very much your help, its works great, my minds just can not accept bashscripts sysntax,thank you for the very well detailed answer – Andrewboy Dec 01 '21 at 01:16