当文本存储在变量中时,如何用新字符串替换“]”?

当文本存储在变量中时,如何用新字符串替换“]”?

我的MWE在这里

#!/bin/bash
num=$(gsettings get org.gnome.settings-daemon.plugins.media-keys custom-keybindings | grep -oE '[0-9]+'|sort -rn|head -n 1)
num=$((num + 1))
echo $num
#gsettings set org.gnome.settings-daemon.plugins.media-keys custom-keybindings "[<altered_list>]"
#gsettings set org.gnome.settings-daemon.plugins.media-keys custom-keybindings "[$key , $key $num]"
key="/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom"
list=$(gsettings get org.gnome.settings-daemon.plugins.media-keys custom-keybindings)
newnum=$(echo "${list}" | grep -oE '[0-9]+' |sort -rn|head -n 1)
echo $newnum
sed -e "/]/${key}${newnum}/" ${list}
#gsettings set org.gnome.settings-daemon.plugins.media-keys custom-keybindings "[$key , $key $num]"
echo $key

我想sed -e "/]/${key}${newnum}/" ${list}这意味着-

['/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom0/', '/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom2/', '/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom1/']   

我想要得到

['/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom0/', '/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom2/', '/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom1/','/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom3/']

custom3在输入中添加额外的内容。

答案1

用于在正则表达式中[]]表示]。用作@sed 表达式分隔符,因为/其中包含替换字符串。

sed -e "s@[]]@${key}${newnum}@" ${list}

您还可以使用反斜杠转义它:

sed -e "s@\]@${key}${newnum}@" ${list}

由于]已知位于字符串的末尾,因此您也可以更改最后一个字符,而不管它是什么:

sed -e "s@.\$@${key}${newnum}@" ${list}

相关内容