Bash 脚本:对特定行号下方的文本组进行排序

Bash scripting: sort groups of text below a specific line number

文本不需要排序 文本不需要排序 文本不需要排序

  example1.com.:
    sources:
      - config
    targets:
      - route53
  test2.co.uk.:
    sources:
      - config
    targets:
      - route53
  another.net.:
    sources:
      - config
    targets:
      - route53
etc.

如果我有一个像上面这样的文件,但有更多的域。使用bash,我怎么能只对“文本不需要排序”下面的文本进行排序,然后也只按域名字母顺序排序而不是每个域组中的文本?

每组由 5 行组成,包括域。

最终结果应如下所示:

  another.net.:
    sources:
      - config
    targets:
      - route53
  example1.com.:
    sources:
      - config
    targets:
      - route53
  test2.co.uk.:
    sources:
      - config
    targets:
      - route53

如有任何帮助,我们将不胜感激!谢谢

尝试以下方法

awk '/^[[:space:]]{2}[[:alpha:]]+.*$/ { key=;next } { yaml[key]=yaml[key]"\n"[=10=] } END { PROCINFO["sorted_in"]="@ind_str_asc";for(i in yaml) { printf "%s%s\n",i,yaml[i] } }' file

分解:

awk '/^[[:space:]]{2}[[:alpha:]]+.*$/ { # Pattern match each line in the file and check for a new line, 2 spaces and then a domain name.
      key=;next                       # Where a match is found, set up an array key and skip to the next line
     } 
     { 
      yaml[key]=yaml[key]"\n"[=11=]         # Set up an array yaml with they key and the value a new line followed by the line
     } 
     END { 
      PROCINFO["sorted_in"]="@ind_str_asc"; # Once the file is processed, sort the index in ascending alphabetical order
      for(i in yaml) {                      
        printf "%s%s\n",i,yaml[i]          # Loop through the yam array and print the sorted index followed by the value
      } 
     }' file