0

I have a string as:

MESSAGES { "Instance":[{"InstanceID":"i-098098"}] } ff23710b29c0220849d4d4eded562770 45c391f7-ea54-47ee-9970-34957336e0b8

I need to extract the part { "Instance":[{"InstanceID":"i-098098"}] } i.e from the first occurence of '{' to last occurence of '}' and keep it in a separate file.

jww
  • 97,681
  • 90
  • 411
  • 885
  • possible duplicate of [Extract substring in bash](http://stackoverflow.com/questions/428109/extract-substring-in-bash) – Luca Davanzo Aug 28 '14 at 06:51

2 Answers2

0

If you have this in a file,

sed 's/^[^{]*//;s/[^}]*$//' file

(This will print to standard output. Redirect to a file or capture into a variable or do whatever it is that you want to do with it.)

If you have this in a variable called MESSAGES,

EXTRACTED=${MESSAGES#*{}
EXTRACTED="{${EXTRACTED%\}*}}"
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Thanks, Triplee it works like charm.can you please expalin the pattern?? – user3744067 Aug 28 '14 at 09:01
  • The `sed` pattern consists of two substitutions: Replace everything before the first brace, and everything after the last one. The shell [parameter expansion](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html) is similar: Remove everything up through the first brace, and everything after the last one (then resupply the removed braces). – tripleee Aug 28 '14 at 09:50
  • @user3744067 `s/^[^{]*//` replaces everything up to the first `{` with nothing. `s/[^}]*$//` replaces everything after the last `}` with nothing. `[^}]*` means every character that is not a `}`. –  Aug 28 '14 at 09:51
  • @Jidder More like "any sequence of characters which are not (newline or) closing brace". – tripleee Aug 28 '14 at 09:53
  • @tripleee whatever floats your boat –  Aug 28 '14 at 10:02
0

I would suggest either sed or awk from this article. But initial testing shows its a little more complicated and you will probably have to use a combination or pipe:

echo "MESSAGES { "Instance":[{"InstanceID":"i-098098"}] } ff23710b29c0220849d4d4eded562770 45c391f7-ea54-47ee-9970-34957336e0b8" | sed 's/^\(.*\)}.*$/\1}/' | sed 's/^[^{]*{/{/'

So the first sed delete everything after the last } and replace it with a } so it still shows; and the second sed delete everything up to the first { and replace it with a { so it still shows.

This is the output I got:

{ Instance:[{InstanceID:i-098098}] }
SysadminB
  • 54
  • 3