使用文件中的第一個可用號碼

使用文件中的第一個可用號碼

我有一個配置文件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))")

相關內容