Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting groups of lines

Say I have this list:

sharpest
  tool
  in
the
  shed
im
  not
  the

How can I order alphabetically by the non-indented lines and preserve groups of lines? The above should become:

im
  not
  the
sharpest
  tool
  in
the
  shed

Similar questions exist here and here but I can't seem to make them work for my example.

Hopeful ideas so far

  • Maybe I could use grep -n somehow, as it gives me the line numbers? I was thinking to first get the line numbers, then order. I guess I'd somehow need to calculate a line range before ordering, and then from there fetch the range of lines somehow. Can't even think how to do this however!
  • sed ranges look promising too, but same deal; sed 1,2p and further examples here.
like image 580
Nick Bull Avatar asked Feb 22 '18 10:02

Nick Bull


People also ask

Can you group rows together in Excel for sorting?

If your dataset contains just one level of information, the fastest way would be to let Excel group rows for you automatically. Here's how: Select any cell in one of the rows you want to group. Go to the Data tab > Outline group, click the arrow under Group, and select Auto Outline.

What is group sorting?

Group sorting is a facility available on table worksheets that removes repeated values to make reports easier to analyze. Group sorting has the following effects: The group name is displayed only once at the start of a group. Repeated group name values are removed from the worksheet.


1 Answers

If perl is okay:

$ perl -0777 -ne 'print sort split /\n\K(?=\S)/' ip.txt
im
  not
  the
sharpest
  tool
  in
the
  shed
  • -0777 slurp entire file, so solution not suitable if input is too big
  • split /\n\K(?=\S)/ gives array using newline character followed by non-whitespace character as split indication
  • sort to sort the array
like image 89
Sundeep Avatar answered Sep 22 '22 06:09

Sundeep