How to reverse order of blocks of text

bash, sorting, text

Solution

In `emacs`, you can use the `sort-paragraphs` command:

Ctrl-xhMeta-xsort-paragraphsEnter

In `vim`: https://superuser.com/questions/365094/sort-file-per-paragraph-in-vim

Use the basic unix tools:

awk -F'\n' -vRS='' -vOFS=',' '{$1=$1}1' input.txt |
    sort |
        tr ',' '\n' |
            sed 's@^/@\n/@'

I use `awk` to transform the data to a `csv`, then `sort` the `csv`, at last I transform the `csv` back to list style.

result:

/Section 1/
Dogs
Rabbits
Lemmings

/Section 2/
Eagles
Mice

/Section 3/
Rabbits
Dogs
Cats

Edit: Sorry, I didn't look at your question very carefully. You can change the `sort` command to `tac` to reverse the order.

Problem

How can I revert the order of some blocks of text using only bash commands like sed and cat? What I want is something like tac, but instead of operating line by line, it would operate block by block. Example: From ``` /Section 3/ Rabbits Dogs Cats /Section 2/ Eagles Mice /Section 1/ Dogs Rabbits Lemmings ``` To ``` /Section 1/ Dogs Rabbits Lemmings /Section 2/ Eagles Mice /Section 3/ Rabbits Dogs Cats ``` In some files, the beginning of the block is marked by a slash, as in the example above. In others, the blocks are marked only by the existence of one or more blank lines between them.

Original source