使用文件中的第一个可用号码

使用文件中的第一个可用号码

我有一个配置文件prosody.config

具有以下数据:

VirtualHost "pubsub.subdomain.domain.com"
admins = { "node1.subdomain.domain.com", "node2.subdomain.domain.com" }
    autocreate_on_subscribe = true
    autocreate_on_publish = true
    modules_enabled = {
        "pubsub";
    }

VirtualHost "subdomain.domain.com"
    authentication = "anonymous"
    modules_enabled = {
        "bosh";
    }
    c2s_require_encryption = false

VirtualHost "auth.subdomain.domain.com"
    authentication = "internal_plain"

admins = { "[email protected]" }

Component "node1.subdomain.domain.com"
    component_secret = "password"
Component "node2.subdomain.domain.com"
    component_secret = "password"
Component "conference.subdomain.domain.com" "muc"
Component "focus.subdomain.domain.com"
    component_secret = "password"

我需要node2.subdomain.domain.com在本例中的编号之后找到第一个可用编号3,并将其回显回相同的配置,例如echo -e "Component \"node3.subdomain.domain.com\"\n component_secret = \"password\"" >> prosody.config

最终的内容应​​该是这样的:

VirtualHost "pubsub.subdomain.domain.com"
    admins = { "node1.subdomain.domain.com", "node2.subdomain.domain.com" }
        autocreate_on_subscribe = true
        autocreate_on_publish = true
        modules_enabled = {
            "pubsub";
        }

    VirtualHost "subdomain.domain.com"
        authentication = "anonymous"
        modules_enabled = {
            "bosh";
        }
        c2s_require_encryption = false

    VirtualHost "auth.subdomain.domain.com"
        authentication = "internal_plain"

    admins = { "[email protected]" }

    Component "node1.subdomain.domain.com"
        component_secret = "password"
    Component "node2.subdomain.domain.com"
        component_secret = "password"
    Component "conference.subdomain.domain.com" "muc"
    Component "focus.subdomain.domain.com"
        component_secret = "password"
    Component "node3.subdomain.domain.com"
        component_secret = "password"
    Component "node4.subdomain.domain.com"
        component_secret = "password"

在这种情况下,每次运行脚本时,数字都会从最大数字增加 1"node4.subdomain.domain.com"

谢谢 !

答案1

短的呆呆地解决方案:

awk -v FPAT="[0-9]+" 'END{print "node"$1+1}' xyz.config

输出:

node4

  • FPAT="[0-9]+"- 匹配字段的正则表达式,而不是匹配字段分隔符

  • END{...}- 仅考虑文件的最后一行

答案2

< xyz.config tail -n 1 | awk 'match($0, /[0-9]+$/) {
  print substr($0, 1, RSTART-1) substr($0, RSTART)+1}'

要获取文件的最后一行,请提取该行末尾的数字,打印数字前面的内容,然后打印组成这些数字的数字,并加一。

您也可以在 中完成整个操作awk,但这意味着完全读取整个文件:

< xyz.config awk 'END {if(match($0, /[0-9]+$/))
  print substr($0, 1, RSTART-1) substr($0, RSTART)+1}'

使用sh运算符:

< xyz.config tail -n1 | (
  IFS= read -r line || exit
  num=${line##*[!0-9]}
  printf '%s\n' "${line%"$num"}$((num + 1))")

相关内容