【问题标题】:Replace Last Occurrence of Substring in String (bash)替换字符串中子字符串的最后一次出现(bash)
【发布时间】:2018-06-26 14:33:02
【问题描述】:

来自 bash 软件手册:

${parameter/pattern/string}

模式被扩展以产生一个 模式就像在文件名扩展中一样。参数被扩展并且 模式与其值的最长匹配被替换为字符串。
...如果模式以'%'开头,它必须匹配 在参数扩展值的末尾。

所以我试过了:

local new_name=${file/%old/new}

其中 string 是绝对文件路径(/abc/defg/hijoldnew 是可变字符串。

然而,这似乎试图匹配文字 %sb1

这个的语法是什么?

预期输出:

给定

old=sb1
new=sb2

然后

/foo/sb1/foo/bar/sb1 应该变成/foo/sb1/foo/bar/sb2

/foo/foosb1other/foo/bar/foosb1bar 应该变成/foo/foosb1other/foo/bar/foosb2bar

【问题讨论】:

  • @anubhava 很快改变了那里的要求,因为我意识到我真正需要什么,尽管它也可以与文字一起使用。

标签: bash shell pattern-matching substring variable-expansion


【解决方案1】:

仅使用 shell-builtin parameter expansion:

src=sb1; dest=sb2
old=/foo/foosb1other/foo/bar/foosb1bar

if [[ $old = *"$src"* ]]; then
  prefix=${old%"$src"*}                  # Extract content before the last instance
  suffix=${old#"$prefix"}                # Extract content *after* our prefix
  new=${prefix}${suffix/"$src"/"$dest"}  # Append unmodified prefix w/ suffix w/ replacement
else
  new=$old
fi

declare -p new >&2

...正确发出:

declare -- new="/foo/foosb1other/foo/bar/foosb2bar"

【讨论】:

    猜你喜欢
    • 2011-04-19
    • 2011-07-26
    • 2019-07-02
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多