Search code examples
vi

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:

.
..
...
        {
        "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.