Last Updated: October 31, 2019
·
894
· tylerhunt

Sorting a Chunk of Lines in Vim

I often find a need to sort lines of text when editing files in Vim. Typically, this is things like lists of gems in a Gemfile or lists of CSS attributes in a Sass stylesheet.

Here's how I do it:

  1. Make a mark on the first line moving the cursor there and hitting mt (You can use a letter other than "t", but I like to remember this as a shortcut for "mark top")
  2. Move the cursor to the bottom line, and type :'t,.!sort.

That's it!

You can use this same mark technique for other operations on groups of lines, too. Here are some examples:

  • d't to delete all the lines from the current line to the t mark
  • :'t,.s/"/'/g to replace all the double quotes in a block with single quotes

1 Response
Add your response

That's neat! Thanks.

over 1 year ago ·