2017-06-02 53 views
0

我有以下模式字符串:<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 
+0

你的JSON里面是否有散列{{}}? – codeforester

+0

我没有得到你显示的输出。你如何将参数传递给脚本? – choroba

+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} 

我猜字符串被传递的命令行没有引用,因此b eing分成多个参数。如果引用命令行参数以防止调用shell(​​而不是./yourscript $string)进行字符串拆分,则会避免此问题。

+0

你在上面的评论中是正确的。这是'$ 1'导致它被切断。万分感谢!请添加到您的答案,所以我可以接受它。 –

+0

@NishantRoy,完成,谢谢。 –

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} 
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的键应以双引号括起来。