How to match string and print lines within curly braces { } from config file

1k Views Asked by At

I want to print the lines within { and } with assign where "mango" in Hostgroups

   object Host "os.google.com" {
    import "windows"
    address = "linux.google.com"
    groups = ["linux"]
    }

    object Host "mango.google.com" {
    import "windows"
    address = "mango.google.com"
    groups = ["linux"]

    assign where "mango" in Hostgroups
    }

Desired output:

    object Host "mango.google.com" {
    import "windows"
    address = "mango.google.com"
    groups = ["linux"]

    assign where "mango" in Hostgroups
    }
3

There are 3 best solutions below

0
Dudi Boy On

Try this awk script

script.awk

/{/,/}/ { #define record range from { to }
    if ($0 ~ "{") rec = $0; # if record opening reset rec variable with current line
    else rec = rec "\n" $0; # else accumulate the current line in rec
    if ($0 ~ /assign where "mango" in Hostgroups/) { # if found exit pattern in current line
        print rec; # print the rec
        exit;      # terminate
    }
}

executions:

awk -f script.awk input.txt

output:

object Host "mango.google.com" {
import "windows"
address = "mango.google.com"
groups = ["linux"]

assign where "mango" in Hostgroups
5
potong On

This might work for you (GNU sed):

sed -n '/{/h;//!H;/}/{g;/assign where "mango" in Hostgroups/p}' file

Turn off seds automatic printing using the -n option and gather up lines in the hold space between curly braces. Following the closing curly brace, replace it with the contents of the hold space and if there is a match for assign where "mango" in Hostgroup print it.

0
Ed Morton On

Assuming } doesn't appear in any other context in your input:

$ awk -v RS='}' '
    /assign where "mango" in Hostgroups/ {
        sub(/^[[:space:]]+\n/,"")
        print $0 RS
    }
' file
    object Host "mango.google.com" {
    import "windows"
    address = "mango.google.com"
    groups = ["linux"]

    assign where "mango" in Hostgroups
    }