Vim: sorting using multiple templates

I know that in vim I can sort the file using a regular expression to indicate which parts of each line that I want to use for consideration when sorting using:

:sort 'regex' r 

Is it possible to combine more than one expression?

Here you have an example:

INPUT:

 bar a 2 foo b 1 bar b 1 foo a 2 

: sort '[az]' r

 foo b 1 bar b 1 bar a 2 foo a 2 

sort '[0-9]' r

 bar a 2 bar b 1 foo b 1 foo a 2 

EXPECTED (maybe something like ": sort" [AZ] | [0-9] 'r?):

 bar b 1 bar a 2 foo b 1 foo a 2 

Note that bare β€œsorting” does not work due to β€œa” and β€œb”, which upset the numbers

 bar a 2 bar b 1 foo a 2 foo b 1 

An alternative outside VIM is also accepted, but for the sake of curiosity, I would like to know if it is really possible to do this in VIM (and if afermative, how ;-)

Thanks a lot, Relations

+8
sorting vim regex
source share
2 answers

Assuming you have an external sort, the following should work:

 :%!sort -k1,1 -k3,3n 

EDIT: Explanation:

-k used to specify sort keys. -k1,1 implies the start of sorting by key1 and the end of key1 . -k3,3n means start sorting by key3 and end key3 ; n here denotes a numerical sort, that is, a comparison according to the numerical value of the string.

By default, sorting takes an empty space into a blank transition as a field separator. Thus, he will consider the string bar b 1 , consisting of three fields. If the values ​​were limited to a specific character other than a space, say : you must specify a field separator by adding -t:

+6
source share

There is a flaw in what you ask for ... If you want to sort by the first word AND, then you need to somehow specify the priority order. In other words, you want the sorted list to look like this:

 bar b 1 bar a 2 foo b 1 foo a 2 

or that:

 bar b 1 foo b 1 bar a 2 foo a 2 

Obviously, the answer is first. But you have to tell vim that! Therefore, I cannot think of any (reasonable) way to do this in one command ... But I can do this in two:

 :sort /\d/ r :sort /[az]/ r 

By executing commands in this order, you indicate that the first word takes precedence over the number.

+2
source share

All Articles