打印特定的单词,直到文件中匹配字符串(模式1)上方的匹配字符串(模式2)

时间:2019-06-22 12:31:40

标签: linux string

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
}

我要在匹配的字符串上方打印行,直到文件中的特定模式

例如:

我要在主机组中的分配“ mango”位置上方打印行,直到文件中的这种模式 {

所需的输出:

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

assign where "mango" in Hostgroups

1 个答案:

答案 0 :(得分:0)

尝试使用此awk脚本

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
    }
}

执行:

awk -f script.awk input.txt

输出:

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

assign where "mango" in Hostgroups