Print a specific words till matched string ( patte

2019-08-24 04:02发布

问题:

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
}

I want to print the lines above the matched string till the specific pattern in a file

Ex:

I want to print the lines above the assign where "mango" in Hostgroups till this pattern { in the file

Desired output:

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

assign where "mango" in Hostgroups

回答1:

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


标签: linux string