对文本文件中的节进行排序

对文本文件中的节进行排序

我有一个包含以下格式的许多节的文件。请注意每节之间的空行。我希望能够对此文件进行排序,以便完成的文件是按索引名称的字母顺序排列的每个节。这可以做到吗?

[monitor:///..]
disabled = true
index = abc
sourcetype= ...

[monitor:///...]
disabled = true
index = def
sourcetype= ...

答案1

使用

gawk -v RS="" '
  match($0, /index = ([^[:space:]]+)/, m) {
    stanzas[m[1]] = $0
  }
  END {
    PROCINFO["sorted_in"] = "@ind_str_asc"
    ORS = "\n\n"
    for (indx in stanzas) print stanzas[indx]
  }
' file

让我们在文件中添加另一节:

[monitor:///..]
disabled = true
index = xyz
sourcetype= ...

[monitor:///..]
disabled = true
index = abc
sourcetype= ...

[monitor:///...]
disabled = true
index = def
sourcetype= ...

然后 gawk 命令的结果是

[monitor:///..]
disabled = true
index = abc
sourcetype= ...

[monitor:///...]
disabled = true
index = def
sourcetype= ...

[monitor:///..]
disabled = true
index = xyz
sourcetype= ...

(末尾有一个空行)

参考文献:

答案2

用 dirkt 的评论制作的 Bash 函数:

function sort_stanzas() {
    declare file_path="$1"
    cat "$file_path" \
        | sed -z \
            -e 's/\n/\t/g' \
            -e 's/\t\t/\n/g' \
        | sort \
        | sed -z \
            -e 's/\n/\t\t/g' \
            -e 's/\t/\n/g'
}

用法:sort_stanzas <file>

相关内容