hello -
i am trying to take a text file with multiple sets of numbered lines and sort each set, leaving the non-numbered text in place. i can't seem to figure out how to loop over the regular text, save then sort the numbered text, then move on. i want to take a file like this:

test
001
003
002
004
test
020
022
024
023

and make a file like this:

test
001
002
003
004
test
020
022
023
024

so far only have this for sorting individual number blocks:

$datafile = "/Users/path/file";
open(DAT, $datafile);
@dataarray = <DAT>;
@grep = grep(/^\d/, @dataarray);
@sort = sort @grep;
print @sort;

but i can't seem to incorporate this into a full script (and i know there's a more succinct way to write that...it's just the best i could do and have work). is there an easy way to do this that i'm missing? or do i have to write a complicated match? i'd love anyone's input on this - i've tried snooping around but haven't found this problem. thank you in advace!

Do the groups of lines with numbers break at the lines with text? In other words, do you only sort the numbers up to "test" as a group, and then sort the next set of lines with numbers until the next line with "test" or does the sorting of the numbers need to be done as one continuous group?

If the lined numbers are discrete groups you can continue storing them in an array until you get to a line with text. You then sort the group of numbers and print them to a file and then print the line of text last, or push it all into a larger array and continue like this this until the entire file is read and sorted.

If the entire file needs to be sorted yet the lines with text need to stay in their original position you will need to store the position (the line number I guess) in a hash, then sort all the numbered lines, then print the sorted numbers back to the file but keeping track of the line numbers as you go and insert the text back as needed.

But one thing I am pretty sure of, you will not be able to accomplish this with a single sort.

This article has been dead for over six months. Start a new discussion instead.