[英]Bash scripting: sort groups of text below a specific line number
Text does not need sorting Text does not need sorting Text does not need sorting文本不需要排序 文本不需要排序 文本不需要排序
example1.com.:
sources:
- config
targets:
- route53
test2.co.uk.:
sources:
- config
targets:
- route53
another.net.:
sources:
- config
targets:
- route53
etc.
If I have a file like the above but with many more domains.如果我有一个像上面这样但有更多域的文件。 Using bash, how could I only sort the text below the "Text does not need sorting" and then also only sort alphabetically by the domain names and not the text in each domain group?
使用 bash,我怎么能只对“文本不需要排序”下面的文本进行排序,然后也只按域名的字母顺序而不是每个域组中的文本排序?
Each group would consist of 5 lines including the domain.每组将由 5 行组成,包括域。
The end result should look like:最终结果应如下所示:
another.net.:
sources:
- config
targets:
- route53
example1.com.:
sources:
- config
targets:
- route53
test2.co.uk.:
sources:
- config
targets:
- route53
Any help would be greatly appreciated.任何帮助将不胜感激。 Thanks.
谢谢。
Try the following尝试以下
awk '/^[[:space:]]{2}[[:alpha:]]+.*$/ { key=$1;next } { yaml[key]=yaml[key]"\n"$0 } END { PROCINFO["sorted_in"]="@ind_str_asc";for(i in yaml) { printf "%s%s\n",i,yaml[i] } }' file
Breaking it down:分解它:
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=$1;next # Where a match is found, set up an array key and skip to the next line
}
{
yaml[key]=yaml[key]"\n"$0 # 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.