我有一个包含以下格式的许多节的文件。请注意每节之间的空行。我希望能够对此文件进行排序,以便完成的文件是按索引名称的字母顺序排列的每个节。这可以做到吗?
[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= ...
(末尾有一个空行)
参考文献:
- 内置字符串函数对于 3 参数
match()
- 通过 gawk 使用预定义的数组扫描顺序
答案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>