Monday, April 22, 2013

Sort Me A Column

Need to sort a column within your table without messing with the other columns?
Vim has your back with blockwise visual selections and a bit of gymnastics.

Sample table:
1 this 1 apple    is 1
2 this 4 durian   is 2
3 this 3 carrot   is 3
4 this 2 banana   is 4
5 this 5 eggplant is 5

Desired result:
1 this 1 apple    is 1
2 this 2 banana   is 2
3 this 3 carrot   is 3
4 this 4 durian   is 4
5 this 5 eggplant is 5

[wrong] Result of naive :sort command:
1 this 1 apple    is 1
2 this 4 durian   is 2
3 this 3 carrot   is 3
4 this 2 banana   is 4
5 this 5 eggplant is 5

[wrong] Result of :sort /^. / command (to skip leading numbers):
1 this 1 apple    is 1
4 this 2 banana   is 4
3 this 3 carrot   is 3
2 this 4 durian   is 2
5 this 5 eggplant is 5

A Solution

  1. Visually select the column of interest with ctrl-v
  2. Cut it with x
  3. Open a temporary scratch buffer with :enew
  4. Paste with p
  5. Sort with :sort
  6. If you need to, ensure your cursor is line 1, col 1 with gg0
  7. Visually select and yank everything, blockwisely with ctrl-vG$y
  8. Switch back to where you came from with ctrl-6 (ctrl-^)
  9. Jump to the start of your original cut with `[
  10. Paste with P

No comments:

Post a Comment