Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
add comment

2 Answers

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
add comment

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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.