Home > Mobile >  How do I unfold brackets using vim command with sed? - Sed Replace character with newline unless fir
How do I unfold brackets using vim command with sed? - Sed Replace character with newline unless fir

Time:06-18

I've got this config file that I'd like to unfold it's brackets from. As far as I can tell I can best use the vim -e -c 'stuff goes here' command for this and put that inside a shell script.

Input file

["12000xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx12000",["127.0.0.1:12000"]]

It should look like this.

Desired output

[
"12000xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx12000",
[
"127.0.0.1:12000"
]
]

Well actually, that's just the first step, but I've got those mostly figured out using gg=G.

This command used when testing in vim itself:

:%s/^\[/\[\r/|%s/[^^]\[/\r\[\r/g|%s/\]/\r\]/g

And below is what I get to see

Output file

[
"12000xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx12000"
[
"127.0.0.1:12000"
]
]

My main issue right now is that my bracket replacement sed command replaces two characters instead of one. I figured that the s/[^^]\[/\r\[\r/g part of my code is wrong.

It looks at a pattern of two characters, a first character should not be the first character of the line and a second character should be an opening bracket.

That's however not what I want. I just want to look at opening brackets and only replace them if they are not the first character.

How would I do that?

CodePudding user response:

This sed may work

$ sed s'/\[\([^][]*\)/[\n\1\n/g;s/]/&\n/' input_file
[
"12000xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx12000",
[
"127.0.0.1:12000"
]
]

Or vim

:s/\[\([^][]*\)/[\r\1\r/g|s/]/&\r/
  • Related