To sort lines in Vim, you can use the built-in sort command that sorts lines by a defined range. Typically, all the lines in the document are sorted if no range is given.
For example, if you want to sort the entire document, use the :sort command in NORMAL mode. On the other hand, if you only want to sort specific lines, use the :x,y sort command, where x and y define the range from line number x to y.
Sorting is one of the crucial functionalities that is required while editing documents. Vim is no less than any advanced editor when it comes to providing unique features like sorting. Therefore, in this guide, I will be explaining Vim’s built-in sort command, and how to use it in different ways to sort lines.
Note: The instructions and commands mentioned in this guide are performed on Linux (Ubuntu 22.04). Vim is a cross-platform text editor, and these commands will work without any error on macOS and Windows as well.
Sort All the Lines
To sort all the lines in a document, execute the sort command in the NORMAL mode.
By default, the sort command will sort lines in lexicographic order.
Note that if your file has empty lines, then the sort command will place the empty lines at the top actual text sort.
Sort Selected Lines
To sort the selected lines, first, we have to select them in the selection mode. And to enable the selection mode, press v, and select lines using the h, j, k, and l keys or directional buttons.
Vim also has a line-specific selection mode called VISUAL LINE mode. Press V (shift+v) to enable the VISUAL LINE mode to select the lines.
After selecting the lines, you will view ‘<,‘> in the command line, which represents the selection range. The ‘< indicated the first line of visual selection, while ‘> indicates the last.
Now, just type the sort command, and press the return key to apply the sort on the selected lines as shown in the following GIF.
Sort the Ranged Lines
The line range can be passed before the sort command to sort the lines. The :set number command can be used to activate the line number in Vim, hence making it easier to identify the line number.
For example, to sort lines from line number 1 to line number 4, use the :1,4 sort command.
As can be seen in the above output that the only specified lines are sorted.
Sort in Reverse
As mentioned earlier, the default behavior of the sort command is to sort the lines in lexicographic order. To sort the lines in a non-lexical manner, add the exclamation mark (!) after the sort command.
Sort by Locale
Computers are operated all over the world, having different languages with different sets of characters and rules. When it comes to sorting the collation by locale matters. For example, if you are living in Japan and want to sort the lines by that locale, then you have to specify it. The sort command also provides to set the locale option with the l flag.
To check the current collation locale, use the :language command.
To sort with the current locale use:
Note: This option may not work properly on systems based on macOS.
Sort by Number
To sort lines based on the first decimal number in a line, use the n flag with the sort command. The sorting will proceed in ascending order by default.
To sort in descending order, use the ! symbol after the command.
The difference between sort and sort n is that the sort command sorts the lines lexically, ignoring the numbers in them. If you want to sort with respect to the numbers, then append the n flag with the sort command.
For example, the lines in the following file have letters and numbers as well. When we sort it by applying the sort command only, these lines will be sorted alphabetically. On the other hand, applying the sort n command sort the lines by number as shown in the following image.
Some other options for numerical sorting are mentioned in the following table.
f | Float number sorting |
b | Binary number sorting |
o | Octal number sorting |
h | Hexadecimal number sorting |
Sort by Marks
In Vim, marks are used to set specific positions in the file for easier navigation of a file with hundreds of lines. The marks can be used to perform a sort operation using the sort command.
Suppose you have set two marks a and b.
So, to sort all the lines from mark a to mark b, use the following command.
The single quote (‘) is used to access the marks.
Sort by Regular Expression (RegEx)
The regular expression (RegEx) is one of the common ways to sort lines by defining a pattern with the sort command.
For example, to sort the lines with respect to a column that has alphabets and digits, use the /[a-z]*[0-9]+/ pattern with the sort command. The r flag after the sort command is used to instruct the command to sort based on the mentioned pattern.
As you can see in the above image, the last column is sorted alphabetically. To sort the column numerically, just insert the n flag.
Note: I skipped the first lines by defining the range from line 2,5.
The r flag allows you to sort the file by the given patterns. Without the r flag, the sort command will sort all the lines that do not match the pattern.
Remove the Duplicate Lines
The quickest way to remove the duplicate lines in a file is using the sort command with the u flag, which represents the unique.
Note that using this method to remove duplicate lines will also sort the lines, which can be unwanted in many situations. Use alternative methods, such as regex, to remove duplicate lines in a file without the need for sorting.
Sort Lines Based on a Column
There are two methods to sort lines in Vim based on column. The first method uses the external Linux sort command, while the second uses the built-in sort command.
The external command is easy to implement compared to the default sort command. Note that the external commands are not the default commands of Vim. It means any command that is supported by the operating system.
Let’s understand how it works in Vim.
To use any external command in Vim, ! symbol is used before that command. Assume we have a comma-separated file (CSV) and want to sort the file with respect to the third column. The command will be
The % indicates the entire buffer as a selection. The -t flag is used to define the field separator, which can be a comma, colon, or even space. The -k flag is the key that indicates the position in the line, and k2 means the second field after the specified delimiter.
In the example, I have mentioned the range instead of % to skip the first line.
The external sort command can be useful in many other ways as well because it offers various sorting options such as shuffling, random sorting, and merging. To learn more about the Linux sort command, use the man help command.
On the other hand, to use Vim’s built-in sort command, a regular expression pattern will be employed with the sort command.
In the above command:
- \v represents the vertical tab
- ^ indicates the beginning of the line
- (.{-},) is a group that will in which .{-} is a non-greedy version of .* and , is the separation field
- {2} is representing the first 2 columns to skip
It can be seen that the r flag is not used with the pattern, which means the pattern will skip any matched column and sort the columns after the pattern. In this case, the file will be sorted based on the third column. Again in the following example, to skip the first line, I used the range 2,5.
The basic distinction between .* and .{-} is that the .{-} will process the shortest match first algorithm, while .* will match as much as possible. For example, in a string wxyz the x.*y will match the entire string while x.{-}y will match the xy only.
Sort Lines Case Insensitive
If you sort lines that start with upper and lower letters, then the sort command will sort lines in the uppercase letters first. Well, to ignore the case sensitivity, use the i flag.
As you can see in the following image, the unsorted and sorted lines with both the :sort and :sort i commands.
Conclusion
Sorting in Vim can easily be done using the Vim built-in sort command. By default, lines are sorted alphabetically, however, if you want to sort in reverse then use the ! sign after the command. The sort command typically sorts the entire buffer; a range can also be defined with a comma separator. The n flag is used for numerical sorting, while to remove the duplicate lines u flag is used. Moreover, to enhance the sorting process, the external sort command can also be used in Vim.
To learn more about sorting in Vim, run the :help sort command.