Reputation: 83
I'm attempting to delete square bracket and convert the strings below:
{"id":1","color": ["green","red", "blue"]}, {"id":2, color:black}
become:
{"id":1","color": "green,red,blue"}, {"id":2, color:black}
I have tried this code but still get an error :
sed: -e expression #1, char 39: Unmatched ) or )
sed 's/\("color"\):[\([a-z0-9]*\)]/\1:"\2"/g'
How do I fix this?
Upvotes: 1
Views: 323
Reputation:
if your data in 'd' file, try gnu sed:
sed -E 'h;s/.*\[([^]]*)\].*/\1/;s/"//g; G;s/(.*)\n(.*)\[[^]]*\](.*)/\2"\1"\3/' d
Upvotes: 0
Reputation: 627507
You may use
sed ':a;s/\(\[[^][]*\)",[ \t]*"/\1,/;ta ; s/\("color"\):[ \t]*\[\([^][]*\)]/\1:\2/g;' file > newfile
See the online sed demo.
:a;s/\(\[[^][]*\)",[ \t]*"/\1,/;ta
Details
:a
- labels/\(\[[^][]*\)",[ \t]*"/\1,/
:
\(\[[^][]*\)
- finds and captures into Group 1 any 0 or more chars other than ]
and [
",
- a ",
substring[^ \t]*
- zero or more chars other than space and tab "
- a "
char\1,
- replaces with the Group 1 contents + a commata
- loop to :a
label if there was a match at the preceding iteration.s/\("color"\):[ \t]*\[\([^][]*\)]/\1:\2/g
Details
\("color"\)
- matches and captures into Group 1 a "color"
substring:
- a colon[ \t]*
- 0+ tabs or spaces\[
- a [
char\([^][]*\)
- Group 2: any 0+ chars other than ]
and [
]
- a ]
char\1:\2
- replaces with Group 1 value, :
, Group 2 valueg
- all occurrences.Upvotes: 1