Bash子串删除

时间:2017-06-02 22:28:43

标签: json regex bash substring

我有以下模式的字符串:<SOMETHING_1>{<JSON>}<SOMETHING_2>

我想保留<JSON>并删除<SOMETHING_X>块。我试图通过删除子字符串来实现它,而不是获取

{x:1,action:PLAYING,name:John,description:Some description rSxv9HiATMuQ4wgoV2CGxw}

我一直在

{x:1,action:PLAYING,name:John,description:Some}

因为说明字段中的空格会切断子字符串。

关于改变什么的任何想法?

CODE:

string="000{x:1,action:PLAYING,name:John,description:Some description rSxv9HiATMuQ4wgoV2CGxw}401"
string=$1
string=$(echo "${string#*{}")
string=$(echo "${string%}*}")
string={$string}
echo $string

3 个答案:

答案 0 :(得分:1)

如果我们接受字符串的直接赋值,原始代码就可以正常工作 - 尽管以下内容更为明确:

string="000{x:1,action:PLAYING,name:John,description:Some description rSxv9HiATMuQ4wgoV2CGxw}401"
string='{'"${string#*"{"}"  # trim content up to and including the first {, and replace it
string="${string%'}'*}"'}'  # trim the last } and all after, and replace it again
printf '%s\n' "$string"

......正确发出:

{x:1,action:PLAYING,name:John,description:Some description rSxv9HiATMuQ4wgoV2CGxw}

我猜测字符串是在未加引号的命令行上传递的,因此被分成多个参数。如果引用命令行参数以防止调用shell(./yourscript "$string"而不是./yourscript $string)进行字符串拆分,则可以避免此问题。

答案 1 :(得分:0)

使用sed:

string="000{x:1,action:PLAYING,name:John,description:Some description rSxv9HiATMuQ4wgoV2CGxw}401"
sed 's/.*\({.*}\).*/\1/g' <<<$string

输出:

{x:1,action:PLAYING,name:John,description:Some description rSxv9HiATMuQ4wgoV2CGxw}

答案 2 :(得分:0)

你去......

string="000{x:1,action:PLAYING,name:John,description:Some description rSxv9HiATMuQ4wgoV2CGxw}401"
echo "original: ${string}"
string="${string#*\{}"
string="${string%\}*}"
echo "final: {${string}}"

顺便说一句,JSON键应该用双引号括起来。