planetp
planetp

Reputation: 16115

How do I sort a range of lines in a file automatically on save?

I have a file with a header and some sorted lines, separated by a blank line:

# header line 1
# header line 2
# ...

line 1 
line 2
...

How do I sort everything after the header in Vim? Also, how can I make Vim sort the file automatically on each save?

Upvotes: 1

Views: 125

Answers (1)

Eugene Yarmash
Eugene Yarmash

Reputation: 149963

To sort the lines after a blank line in a file you can use the :sort command with a range (remember that ranges may use patterns too):

:/^$/+1;$sort

To make Vim do this every time the file is saved you could use an autocommand. Add this line to your .vimrc:

autocmd BufWritePre /path/to/file :/^$/+1;$sort

Upvotes: 4

Related Questions