[英]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=$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
分解它:
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.