是否可以按1级标题对降价文件进行排序?寻找sed
或类似的命令行解决方案
#B
a content of B
#A
b content of A
为...
#A
b content of A
#B
a content of B
答案 0 :(得分:2)
perl one-liner,为便于阅读而拆分
perl -0777 -ne '
(undef,@paragraphs) = split /^#(?=[^#])/m;
print map {"#$_"} sort @paragraphs;
' file.md
您希望以空行结束文件,因此在#B
之前有一个空行。或者你可以改变
map {"#$_"}
到map {"#$_\n"}
强行插入一个。
答案 1 :(得分:0)
您可以将GNU Awk与PROCINFO["sorted_in"] = "@ind_str_asc"
:
gawk 'BEGIN { PROCINFO["sorted_in"] = "@ind_str_asc"; RS = ""; ORS = "\n\n" }
{ a[$1] = $0 } END { for (i in a) print a[i] }' file
输出:
#A
b content of A
#B
a content of B
参考:
PROCINFO["sorted_in"] If this element exists in PROCINFO, then its value controls the order in which array elements are traversed in for loops. Supported values are "@ind_str_asc", "@ind_num_asc", "@val_type_asc", "@val_str_asc", "@val_num_asc", "@ind_str_desc", "@ind_num_desc", "@val_type_desc", "@val_str_desc", "@val_num_desc", and "@unsorted". The value can also be the name of any comparison function defined as follows:
答案 2 :(得分:0)
您还可以使用此脚本在 3 个级别而不是一个级别上进行排序。它也不会在第一个标题第一次出现之前删除内容。
#!/usr/bin/env perl
local $/;
my $text = <>;
my ($start, @chapters) = split/^#(?=[^#])/m, $text;
print $start;
for (sort @chapters) {
my ($level1, @subchapters) = split/^##(?=[^#])/m;
print "#$level1";
for (sort @subchapters) {
my ($level2, @subsubchapters) = split/^###(?=[^#])/m;
print "##$level2";
print map {"###$_"} sort @subsubchapters;
}
}