Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find and replace only if it matches a string in vi editor

I have a large file:

.
..
...
        {
        "term": "Allow A to B",
        "to_zone" : ["inside"],
        "from_zone" : ["sys"],
        "source" : ["10.10.10.10/32"],
        "destination": ["20.20.20.20/32","30.30.30.30/32"],
        "source_user" : ["any"],
        "category" : ["any"],
        "application" : ["any"],
        "service" : ["application-default"],
        "source_hip" : ["any"],
        "destination_hip" : ["any"],
        "tag" : ["con"],
        "action" : "allow",
        "rule_type" : ["universal"],
        "group_tag" : ["con"],
        "profile_setting" : "alert-only"
        },
...
..
.

I would like to delete only the square brackets ‘[,]’ and leave the quotes quotes ONLY if it matches the line, ‘group_tag’.

The expected result would be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

.
..
...
        {
        "term": "Allow A to B",
        "to_zone" : ["inside"],
        "from_zone" : ["bdd"],
        "source" : ["10.10.10.10/32"],
        "destination": ["20.20.20.20/32","30.30.30.30/32"],
        "source_user" : ["any"],
        "category" : ["any"],
        "application" : ["any"],
        "service" : ["application-default"],
        "source_hip" : ["any"],
        "destination_hip" : ["any"],
        "tag" : ["con"],
        "action" : "allow",
        "rule_type" : ["universal"],
        "group_tag" : "con",
        "profile_setting" : "alert-only"
        },
...
..
.

How do I accomplish this in vi editor?

>Solution :

You can apply a substitution to lines matching a pattern:

:/group_tag/s/[\[\]]//g

The [\[\]] matches a literal open or closing square bracket.

To get all such lines in one go, I think you’d have to use this approach:

:%s/\(^.*group_tag" : \)\[\(.*\)\]\(.*\)/\1\2\3/g

This is matching the whole line, but remembering (using capture groups: \(
and \)) everything except the square brackets. Then we replace the line with
only the remembered capture groups.

But also see the approaches in this
question
.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading