In the following example, there are 3 elements that have to be sorted:
- “[aaa]” and the 4 lines (always 4) below it form a single unit.
- “[kkk]” and the 4 lines (always 4) below it form a single unit.
- “[zzz]” and the 4 lines (always 4) below it form a single unit.
Only groups of lines following this pattern should be sorted; anything before “[aaa]” and after the 4th line of “[zzz]” must be left intact.
from:
This sentence and everything above it should not be sorted.
[zzz]
some
random
text
here
[aaa]
bla
blo
blu
bli
[kkk]
1
44
2
88
And neither should this one and everything below it.
to:
This sentence and everything above it should not be sorted.
[aaa]
bla
blo
blu
bli
[kkk]
1
44
2
88
[zzz]
some
random
text
here
And neither should this one and everything below it.
Maybe not the fastest 🙂 [1] but it will do what you want, I believe:
Here’s a better one:
[1] The first one is something like O(N^2) in the number of lines in the file, since it has to read all the way to the section for each section. The second one, which can seek immediately to the right character position, should be closer to O(N log N).
[2] This takes you at your word that there are always exactly five lines in each section (header plus four following), hence
head -n 5. However, it would be really easy to replace that with something which read up to but not including the next line starting with a ‘[‘, in case that ever turns out to be necessary.Preserving start and end requires a bit more work:
You might want to make a function out of that, or a script file, changing sections.txt to $1 throughout.