使用正则表达式按字母顺序排序标题

时间:2014-05-20 03:59:12

标签: regex vim ex

我有一个标记页面,标题语法为!!!。例如:

!!! Better Heading
This section has a sub-heading
!! Sub-Heading one

!!! Can't think of another one
umm...


!!! A Great Heading
Some text here

我想按字母顺序对文本块进行排序,从!!!开始,在下一个!!!之前完成

我有办法这样做吗?

1 个答案:

答案 0 :(得分:2)

试试这个:

perl -ne 's/^(?!!!!)/###/g; print;' file | sed ':a;N;$!ba;s/\n###/###/g' | sort | sed 's/###/\n/g'

首先标记所有非标题行:

perl -ne 's/^(?!!!!)/###/g; print;' file

!!! Better Heading
###This section has a sub-heading
###!! Sub-Heading one
###
!!! Can't think of another one
###umm...
###
###
!!! A Great Heading
###Some text here

然后删除\n这些行:

perl -ne 's/^(?!!!!)/###/g; print;' file | sed ':a;N;$!ba;s/\n###/###/g' 

!!! Better Heading###This section has a sub-heading###!! Sub-Heading one###
!!! Can't think of another one###umm...######
!!! A Great Heading###Some text here

然后使用\n对标记进行排序和替换:

perl -ne 's/^(?!!!!)/###/g; print;' file | sed ':a;N;$!ba;s/\n###/###/g' | sort | sed 's/###/\n/g'

!!! A Great Heading
Some text here
!!! Better Heading
This section has a sub-heading
!! Sub-Heading one

!!! Can't think of another one
umm...