【问题标题】:How to match string and print lines within curly braces { } from config file如何从配置文件中匹配花括号 {} 中的字符串和打印行
【发布时间】:2019-11-05 03:42:26
【问题描述】:

我想用 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
    }

期望的输出:

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

    assign where "mango" in Hostgroups
    }

【问题讨论】:

标签: bash shell awk sed icinga


【解决方案1】:

试试这个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

【讨论】:

    【解决方案2】:

    这可能对你有用(GNU sed):

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

    使用-n 选项关闭seds 自动打印,并在大括号之间的保持空间中收集行。在右花括号之后,将其替换为保留空间的内容,如果与 assign where "mango" in Hostgroup 匹配,则打印它。

    【讨论】:

    • Linux 标签已被移除(原因不明)。你应该提供一个非 GNU 的答案。
    • @jww 据我所知,该解决方案适用于野外的大多数 sed。然而,由于我只使用 GNU 版本对其进行了测试,我觉得有必要提供合格的消息。
    • Solaris 结果为 sed: command garbled: /{/h;//!H;/}/{g;/assign where "mango" in Hostgroups/p}。 OS X 结果为 sed: 1: "/{/h;//!H;/}/{g;/assign ...": extra characters at the end of p command
    • @jww 我对我在 Solaris 和 OS X 上使用 sed 的解决方案表现得像他们一样感到惊讶和难过,但我只能重申might work for you 为我辩护。顺便说一句,也许那些操作系统更喜欢单独使用每个命令,这可以使用-e 选项并删除; 或通过将每个命令放在文件中的单独行并使用-f 选项来实现。
    【解决方案3】:

    假设} 没有出现在您输入的任何其他上下文中:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-18
      • 1970-01-01
      • 2020-06-16
      • 2012-11-23
      • 1970-01-01
      • 2011-07-22
      相关资源
      最近更新 更多