unix 我想读取xml文件和更新行使用awk

pbossiut  于 2023-10-18  发布在  Unix
关注(0)|答案(1)|浏览(184)

我有像下面这样的文件,我想更新“whitelistSelectorRegex”下volumeSelectorConfig节。

volumeMonitorConfig:
    # maxNumberVolumes specifies the maximum number of volumes that the
    # machine agent will monitor.
    maxNumberVolumes           : 5

    # whitelistSelectorRegex specifies the regular expression used to whitelist reported volumes
    # by name. A volume with the name matching the regex will always be reported,
    # with respect to maxNumberVolumes
    whitelistSelectorRegex        : ""

    # blacklistSelectorRegex specifies the regular expression used to blacklist reported volumes
    # by name. A volume with the name matching the regex will never be reported, unless it also
    # matches the whitelistSelectorRegex. By default volumes created by docker storage drivers are blacklisted.
    # For example, /var/lib/docker/devicemapper/a24b981234c1
    blacklistSelectorRegex        : "^/var/lib/docker/.*"

    # samplingInterval indicates how often to gather metric data. Units in milliseconds.
    # This overrides the standard sampling interval. If this is not set the standard sampling
    # interval is used. This is currently supported only on Linux.
    samplingInterval: 3000

networkMonitorConfig:
    # maxNumberNetworks specifies the maximum number of network interface cards that the
    # machine agent will monitor.
    maxNumberNetworks            : 5

    # whitelistSelectorRegex specifies the regular expression used to whitelist reported networks
    # by name. A network with the name matching the regex will always be reported,
    # with respect to maxNumberNetworks.
    whitelistSelectorRegex       : ""

    # blacklistSelectorRegex specifies the regular expression used to blacklist reported networks
    # by name. A network with the name matching the regex will never be reported, unless it also
    # matches the whitelistSelectorRegex. By default, virtual network interfaces are on the blacklist.
    blacklistSelectorRegex       : "^veth.*|^vnet.*"

我尝试了sed,似乎这不是一个好的选择,我发现

iszxjhcz

iszxjhcz1#

一个yaml感知工具会更安全。
假设新的部分开始在一行上,没有前导空格,在sed中可能并不比在awk中更难:

sed '
    /^volumeMonitorConfig/,/^[^[:space:]]/ {
        /whitelistSelectorRegex/ s/".*"/"newregex"/
    }
' inputfile
awk -v r="newregex" '
    /^[^[:space:]]/ { insection=0 }
    /^volumeMonitorConfig/ { insection=1 }
    insection==1 && index($0,"whitelistSelectorRegex") { sub(/".*"/,r) }
    { print }
' inputfile

尽管在sed中转义正则表达式可能更复杂(在这个例子中,我直接嵌入了它)。

相关问题