![当文本存储在变量中时,如何用新字符串替换“]”?](https://linux22.com/image/129343/%E5%BD%93%E6%96%87%E6%9C%AC%E5%AD%98%E5%82%A8%E5%9C%A8%E5%8F%98%E9%87%8F%E4%B8%AD%E6%97%B6%EF%BC%8C%E5%A6%82%E4%BD%95%E7%94%A8%E6%96%B0%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%9B%BF%E6%8D%A2%E2%80%9C%5D%E2%80%9D%EF%BC%9F%20.png)
我的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}