Saturday, February 09, 2013

Vim: Sorting section titles in a file

Here is vim trick to sort section titles in a file. Inspired from a vim book which I read.

Imagine a input file where the sections needs to be sorted. The content of the section needs to be kept intact.

Section Z
Item1
Item2
SectionEnd
Section A
Item1
Item2
SectionEnd 
Section D
Item1
Item2
SectionEnd
Here is the VIM exscript to do the job:

" Mark lines between each Section/End block
:g/^Section/,/^End/-1s/$/@@/
"  Now join the blocks into one line
:g/^Section/,/^End/j
" Sort each block
:%!sort
" Restore the joined lines to original blocks.
:%s/@@ /^M/g

Output file after sourcing the exscript:

Section A
Item1
Item2
End
Section D
Item1
Item2
End
Section Z
Item1
Item2
End



No comments:

Post a Comment