在 Vim 中按段落对文件进行排序

在 Vim 中按段落对文件进行排序

给定一个如下文件:

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.

我该如何告诉 Vim(版本 7)按动物名称的字母顺序对该文件进行排序?不可能吗?否则如何对该文件进行排序?

答案1

是的,你可以在 vim 中做到这一点:

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

输出

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.

您应该使用特殊字符来指示 EOL(除 之外$)!

答案2

还能怎样对这个文件进行排序?

$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.

其中 sortparagraphs 是

#!/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;

可能有更好的 Perl 解决方案,但以上是一个快速答案。

如果文件大于内存,将文件转换为每个动物一行、排序并最终转换回来可能是合理的。

相关内容