2017-06-02 55 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的鍵應以雙引號括起來。