Nishant Roy
Nishant Roy

Reputation: 1141

Bash substring removal

I have strings in the following pattern: <SOMETHING_1>{<JSON>}<SOMETHING_2>

I want to keep the <JSON> and remove the <SOMETHING_X>blocks. I'm trying to do it with substring removal, but instead of getting

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

I keep getting

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

because the whitespace in the description field cuts off the substring.

Any ideas on what to change?

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

Upvotes: 0

Views: 152

Answers (3)

Charles Duffy
Charles Duffy

Reputation: 295403

The original code works perfectly, if we accept a direct assignment of the string -- though the following is a bit more explicit:

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"

...properly emits:

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

I'm guessing that the string is being passed on a command line unquoted, and is thus being split into multiple arguments. If you quote your command-line arguments to prevent string-splitting by the calling shell (./yourscript "$string" instead of ./yourscript $string), this issue will be avoided.

Upvotes: 1

Shammel Lee
Shammel Lee

Reputation: 4475

Here you go…

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

By the way, JSON keys should be surrounded with double quotes.

Upvotes: 0

tso
tso

Reputation: 4924

with sed:

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

output:

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

Upvotes: 0

Related Questions