Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Given a file that looks like:

Crab
  some text that doesn't need sorting.
  more textual descriptination
Albatross
  some text or other
  perhaps a list that needs no sorting:
    1. a
    2. bee
Dolphin
Pterodactyl
  long story about this particular animal.

How would I tell Vim (version 7) to sort this file alphabetically by animal name? Impossible? How else would one sort this file?

share|improve this question
1  
Please accept an answer. – accolade Mar 18 '12 at 21:16

Yeah, you can do it in vim:

:%s/$/$/
:g/^\w/s/^/\r/
:1del t | $put t
:g/^\w/,/^$/-1join!
:sort
:%s/\$/\r/g
:g/^$/d

output

Albatross
  some text or other
  perhaps a list that needs no sorting:
    1. a
    2. bee
Crab
  some text that doesn't need sorting.
  more textual descriptination
Dolphin
Pterodactyl
  long story about this particular animal.

You should use a special char to indicate EOL(other than $)!

share|improve this answer

How else would one sort this file?

$perl sortparagraphs animals.txt

Albatross
  some text or other
  perhaps a list that needs no sorting:
    1. a
    2. bee
Crab
  some text that doesn't need sorting.
  more textual descriptination
Dolphin
Pterodactyl
  long story about this particular animal.

Where sortparagraphs is

#!/usr/local/bin/perl
use strict;
use warnings;

my ($paragraph, @list);
while(<>) {
  if (/^\S/) {
    push @list, $paragraph if $paragraph;
    $paragraph = '';
  }
  $paragraph .= $_;
}
push @list, $paragraph if $paragraph;
print sort @list;

There is probably a better Perl solution but the above is a quick answer.

If the file is larger than memory, it might be sensible to transform the file into a line per animal, sort and finally transform back.

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .