替换字符串中的子字符串
Replace substring in string
我刚刚尝试了我的第一个 bash 脚本,我需要在 url 中找到一个子字符串(在 ? 部分之后)并替换为 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)
它不起作用,我只能找到 ? 的第一个准确度和字符串的长度
这有帮助吗?
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
有关详细信息,请参阅 https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html。
使用参数扩展:
#! /bin/bash
url='https://example.com/tfzzr?uhg'
replace_string=abc
new=${url%\?*}?$replace_string
echo "$new"
${url%\?*}
从 $url
中删除模式(即 ?
及其后的任何内容)。 ?
需要加引号,否则会匹配模式中的单个字符。将百分号加倍以删除可能最长的子字符串,即从第一个 ?
. 开始
我刚刚尝试了我的第一个 bash 脚本,我需要在 url 中找到一个子字符串(在 ? 部分之后)并替换为 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)
它不起作用,我只能找到 ? 的第一个准确度和字符串的长度
这有帮助吗?
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
有关详细信息,请参阅 https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html。
使用参数扩展:
#! /bin/bash
url='https://example.com/tfzzr?uhg'
replace_string=abc
new=${url%\?*}?$replace_string
echo "$new"
${url%\?*}
从$url
中删除模式(即?
及其后的任何内容)。?
需要加引号,否则会匹配模式中的单个字符。将百分号加倍以删除可能最长的子字符串,即从第一个?
. 开始