Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to sort a groups of lines in vim?

Tags:

vim

sorting

As far as I know vim's :sort method will sort each line. I have some code that is in groups of 3 lines. How can I sort this? Please ignore the shitty code, it's a legacy app :'(

I would like to sort by the case 'AF' line but ignore (group) the country and break line

case 'AF':
  country = 'Afghanistan';
  break;,
case 'AL':
  country = 'Albania';
  break;,
case 'DZ':
  country = 'Algeria';
  break;,
case 'AS':
  country = 'American Samoa';
  break;,
case 'AD':
  country = 'Andorra';
  break;,
case 'AO':
  country = 'Angola';
  break;,
case 'AI':
  country = 'Anguilla';
  break;,
case 'AQ':
  country = 'Antarctica';
  break;,
case 'AG':
  country = 'Antigua And Barbuda';
  break;,
case 'AR':
  country = 'Argentina';
  break;,
case 'AM':
  country = 'Armenia';
  break;,
case 'AW':
  country = 'Aruba';
  break;,
case 'AU':
  country = 'Australia';
  break;,
case 'AT':
  country = 'Austria';
  break;,
case 'AZ':
  country = 'Azerbaijan';
  break;,
case 'BS':
  country = 'Bahamas';
  break;,
case 'BH':
  country = 'Bahrain';
  break;,
case 'BD':
  country = 'Bangladesh';
  break;,
case 'BB':
  country = 'Barbados';
  break;,
case 'BY':
  country = 'Belarus';
  break;
like image 640
Joe Woodward Avatar asked Nov 30 '22 22:11

Joe Woodward


1 Answers

A buzzword-compliant version of the solution suggested by @Halst:

  • mark lines
  • join them on a character that doesn't appear in code:

    :'<,'>s/[:;]\zs\n/@/
    
  • mark lines again

  • sort them:

    :'<,'>sort
    
  • mark lines one last time

  • split them on @:

    :'<,'>s/@/\r/g
    

You'll need to fix the last term manually. No need for indent, sort, or any other external program.

You can also avoid marking lines if you move the relevant code to a scrap buffer and re-format it there.

like image 50
Sato Katsura Avatar answered Dec 04 '22 23:12

Sato Katsura