【问题标题】:Replace substring in string [duplicate]替换字符串中的子字符串[重复]
【发布时间】:2022-01-07 16:12:12
【问题描述】:

我刚刚尝试了我的第一个 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)

它不起作用,我只能找到 ? 的第一个精度,以及字符串的长度

【问题讨论】:

  • 为了使算术工作,你必须写$((first+1))
  • 您的代码有多个语法错误。在寻求人工帮助之前尝试shellcheck.net
  • 切线另见useless use of echo

标签: bash ubuntu


【解决方案1】:

这有帮助吗?

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

【讨论】:

  • 非常感谢您的帮助,这个解决方案也很好用
【解决方案2】:

使用参数扩展:

#! /bin/bash

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

new=${url%\?*}?$replace_string
echo "$new"
  • ${url%\?*}$url 中删除模式(即? 及其后的任何内容)。 ? 需要被引用,否则它将匹配模式中的单个字符。将百分号加倍以删除可能的最长子字符串,即从第一个 ? 开始。

【讨论】:

  • 非常感谢您的帮助,效果很好,我的大脑无法接受 bashscripts sysntax,感谢您提供非常详细的答案
猜你喜欢
  • 2014-11-05
  • 2015-10-08
  • 1970-01-01
  • 2013-05-18
  • 2011-10-10
  • 1970-01-01
  • 2017-07-02
  • 2021-06-17
  • 2012-10-05
相关资源
最近更新 更多