Sort a section of a filesort part of a filesort command in unix with numeric sortHow to sort a file based on a section of a fieldFile sort by time issuesort a file in place while still writing to itNumeric sort fails to properly sort fileTerminal sort command options: sort -k1,1GNU sort stable sort when sort does not know sort order

Do Half-elves or half-orc count as Humans for the Favored Enemy class feature?

What is the difference between experimental and amateur built aircraft in the US?

Does the US require any level of apolitical-ness from career federal employees?

Charges from Dollar General have never shown up on my debit card. How can I resolve this?

How were Kurds involved (or not) in the invasion of Normandy?

Can Microsoft employees see my data?

Digit Date Range

Is it allowed to let the engine of an aircraft idle without a pilot in the plane. (For both helicopters and aeroplanes)

How much does freezing grapes longer sweeten them more?

Russian Caesar cipher

How to figure out key from key signature?

Live action sci-fi film on full body transplantation, unwilling victims end up in ape body, leading scientist betrayed

What happens when the Immolation spell is cast on a creature immune to fire damage?

Largest number order in string

Fat Cantor Set with large complement???

Could an American state survive nuclear war?

When was the famous "sudo warning" introduced? Under what background? By whom?

Does code obfuscation give any measurable security benefit?

How to find Enhantments or Artifacts that have multiple effects?

Replace Shimano MT500 Caliper

Moonlight bright enough to see by

Who inspired the character Geordi La Forge?

Why does Principal Vagina say, "no relation" after introducing himself?

Need a function be continuous on a closed interval for the constitution of Intermediate Value Theorem?



Sort a section of a file


sort part of a filesort command in unix with numeric sortHow to sort a file based on a section of a fieldFile sort by time issuesort a file in place while still writing to itNumeric sort fails to properly sort fileTerminal sort command options: sort -k1,1GNU sort stable sort when sort does not know sort order






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;









8

















Is it possible to sort between two strings in a large file ?



e.g.
Current file is as:



 0cf Front Brake
0d0 Rear Brake
0ce Handle Bars
HUT 03 VR Controls
009 Vest
001 Belt
002 Body Suit
020 Stereo Enable
003 Flexor
007 Hand Tracker
004 Glove
006 Head Mounted Display
008 Oculometer
00a Animatronic Device
000 Unidentified
021 Display Enable
005 Head Tracker
HUT 04 Sport Controls
000 Unidentified
002 Golf Club
001 Baseball Bat


And the desired output is as:



 0ce Handle Bars
0cf Front Brake
0d0 Rear Brake
HUT 03 VR Controls
000 Unidentified
001 Belt
002 Body Suit
003 Flexor
004 Glove
005 Head Tracker
006 Head Mounted Display
007 Hand Tracker
008 Oculometer
009 Vest
00a Animatronic Device
020 Stereo Enable
021 Display Enable
HUT 04 Sport Controls
000 Unidentified
001 Baseball Bat
002 Golf Club


Here, Section HUT 03 VR Controls and HUT 04 Sports Controls is sorted out.



In given file, Section headers starts with non-space characters while section content always begins with space or tab. Since this file have 100+ sections then it will not be feasible to hard-code section name in script/command










share|improve this question




























  • Are the sections on fixed line numbers, or defined by patterns?

    – Sparhawk
    May 16 at 7:33











  • Section headers starts as a first character of line, while it's contents begins with space/tab. Sections are not on fixed numbers.

    – SHW
    May 16 at 7:36











  • Are you wanting to sort one section only (as per title of question and text), or every section?

    – Kusalananda
    May 16 at 8:06











  • @Kusalananda I agree the question is ambiguous on this point; the example output however does show all sections (or parts thereof) being sorted.

    – Stephen Kitt
    May 16 at 8:17











  • I wouldn't say that "HUT" uses hex characters.

    – jlliagre
    May 16 at 9:00

















8

















Is it possible to sort between two strings in a large file ?



e.g.
Current file is as:



 0cf Front Brake
0d0 Rear Brake
0ce Handle Bars
HUT 03 VR Controls
009 Vest
001 Belt
002 Body Suit
020 Stereo Enable
003 Flexor
007 Hand Tracker
004 Glove
006 Head Mounted Display
008 Oculometer
00a Animatronic Device
000 Unidentified
021 Display Enable
005 Head Tracker
HUT 04 Sport Controls
000 Unidentified
002 Golf Club
001 Baseball Bat


And the desired output is as:



 0ce Handle Bars
0cf Front Brake
0d0 Rear Brake
HUT 03 VR Controls
000 Unidentified
001 Belt
002 Body Suit
003 Flexor
004 Glove
005 Head Tracker
006 Head Mounted Display
007 Hand Tracker
008 Oculometer
009 Vest
00a Animatronic Device
020 Stereo Enable
021 Display Enable
HUT 04 Sport Controls
000 Unidentified
001 Baseball Bat
002 Golf Club


Here, Section HUT 03 VR Controls and HUT 04 Sports Controls is sorted out.



In given file, Section headers starts with non-space characters while section content always begins with space or tab. Since this file have 100+ sections then it will not be feasible to hard-code section name in script/command










share|improve this question




























  • Are the sections on fixed line numbers, or defined by patterns?

    – Sparhawk
    May 16 at 7:33











  • Section headers starts as a first character of line, while it's contents begins with space/tab. Sections are not on fixed numbers.

    – SHW
    May 16 at 7:36











  • Are you wanting to sort one section only (as per title of question and text), or every section?

    – Kusalananda
    May 16 at 8:06











  • @Kusalananda I agree the question is ambiguous on this point; the example output however does show all sections (or parts thereof) being sorted.

    – Stephen Kitt
    May 16 at 8:17











  • I wouldn't say that "HUT" uses hex characters.

    – jlliagre
    May 16 at 9:00













8












8








8


1






Is it possible to sort between two strings in a large file ?



e.g.
Current file is as:



 0cf Front Brake
0d0 Rear Brake
0ce Handle Bars
HUT 03 VR Controls
009 Vest
001 Belt
002 Body Suit
020 Stereo Enable
003 Flexor
007 Hand Tracker
004 Glove
006 Head Mounted Display
008 Oculometer
00a Animatronic Device
000 Unidentified
021 Display Enable
005 Head Tracker
HUT 04 Sport Controls
000 Unidentified
002 Golf Club
001 Baseball Bat


And the desired output is as:



 0ce Handle Bars
0cf Front Brake
0d0 Rear Brake
HUT 03 VR Controls
000 Unidentified
001 Belt
002 Body Suit
003 Flexor
004 Glove
005 Head Tracker
006 Head Mounted Display
007 Hand Tracker
008 Oculometer
009 Vest
00a Animatronic Device
020 Stereo Enable
021 Display Enable
HUT 04 Sport Controls
000 Unidentified
001 Baseball Bat
002 Golf Club


Here, Section HUT 03 VR Controls and HUT 04 Sports Controls is sorted out.



In given file, Section headers starts with non-space characters while section content always begins with space or tab. Since this file have 100+ sections then it will not be feasible to hard-code section name in script/command










share|improve this question

















Is it possible to sort between two strings in a large file ?



e.g.
Current file is as:



 0cf Front Brake
0d0 Rear Brake
0ce Handle Bars
HUT 03 VR Controls
009 Vest
001 Belt
002 Body Suit
020 Stereo Enable
003 Flexor
007 Hand Tracker
004 Glove
006 Head Mounted Display
008 Oculometer
00a Animatronic Device
000 Unidentified
021 Display Enable
005 Head Tracker
HUT 04 Sport Controls
000 Unidentified
002 Golf Club
001 Baseball Bat


And the desired output is as:



 0ce Handle Bars
0cf Front Brake
0d0 Rear Brake
HUT 03 VR Controls
000 Unidentified
001 Belt
002 Body Suit
003 Flexor
004 Glove
005 Head Tracker
006 Head Mounted Display
007 Hand Tracker
008 Oculometer
009 Vest
00a Animatronic Device
020 Stereo Enable
021 Display Enable
HUT 04 Sport Controls
000 Unidentified
001 Baseball Bat
002 Golf Club


Here, Section HUT 03 VR Controls and HUT 04 Sports Controls is sorted out.



In given file, Section headers starts with non-space characters while section content always begins with space or tab. Since this file have 100+ sections then it will not be feasible to hard-code section name in script/command







sort






share|improve this question
















share|improve this question













share|improve this question




share|improve this question








edited May 16 at 9:47









Jeff Schaller

50.3k11 gold badges74 silver badges167 bronze badges




50.3k11 gold badges74 silver badges167 bronze badges










asked May 16 at 7:05









SHWSHW

8,7795 gold badges42 silver badges73 bronze badges




8,7795 gold badges42 silver badges73 bronze badges















  • Are the sections on fixed line numbers, or defined by patterns?

    – Sparhawk
    May 16 at 7:33











  • Section headers starts as a first character of line, while it's contents begins with space/tab. Sections are not on fixed numbers.

    – SHW
    May 16 at 7:36











  • Are you wanting to sort one section only (as per title of question and text), or every section?

    – Kusalananda
    May 16 at 8:06











  • @Kusalananda I agree the question is ambiguous on this point; the example output however does show all sections (or parts thereof) being sorted.

    – Stephen Kitt
    May 16 at 8:17











  • I wouldn't say that "HUT" uses hex characters.

    – jlliagre
    May 16 at 9:00

















  • Are the sections on fixed line numbers, or defined by patterns?

    – Sparhawk
    May 16 at 7:33











  • Section headers starts as a first character of line, while it's contents begins with space/tab. Sections are not on fixed numbers.

    – SHW
    May 16 at 7:36











  • Are you wanting to sort one section only (as per title of question and text), or every section?

    – Kusalananda
    May 16 at 8:06











  • @Kusalananda I agree the question is ambiguous on this point; the example output however does show all sections (or parts thereof) being sorted.

    – Stephen Kitt
    May 16 at 8:17











  • I wouldn't say that "HUT" uses hex characters.

    – jlliagre
    May 16 at 9:00
















Are the sections on fixed line numbers, or defined by patterns?

– Sparhawk
May 16 at 7:33





Are the sections on fixed line numbers, or defined by patterns?

– Sparhawk
May 16 at 7:33













Section headers starts as a first character of line, while it's contents begins with space/tab. Sections are not on fixed numbers.

– SHW
May 16 at 7:36





Section headers starts as a first character of line, while it's contents begins with space/tab. Sections are not on fixed numbers.

– SHW
May 16 at 7:36













Are you wanting to sort one section only (as per title of question and text), or every section?

– Kusalananda
May 16 at 8:06





Are you wanting to sort one section only (as per title of question and text), or every section?

– Kusalananda
May 16 at 8:06













@Kusalananda I agree the question is ambiguous on this point; the example output however does show all sections (or parts thereof) being sorted.

– Stephen Kitt
May 16 at 8:17





@Kusalananda I agree the question is ambiguous on this point; the example output however does show all sections (or parts thereof) being sorted.

– Stephen Kitt
May 16 at 8:17













I wouldn't say that "HUT" uses hex characters.

– jlliagre
May 16 at 9:00





I wouldn't say that "HUT" uses hex characters.

– jlliagre
May 16 at 9:00










5 Answers
5






active

oldest

votes


















7


















In Python:



#!/usr/bin/python3

with open("file.txt", "r") as ins:
lines = []
for line in ins:
if line.startswith((" ", "t")):
lines.append(line)
else:
lines.sort()
print(*lines, end = "", sep = "")
print(line, end = "")
lines = []
lines.sort()
print(*lines, end = "", sep = "")


This sorts all the sections (separately), not only those between two specific lines.






share|improve this answer


























  • Superb! This is masterstroke.

    – SHW
    May 16 at 8:01


















6


















For the fun, here is a way to sort a single section using ex:



ex file <<%
/HUT
+1,/HUT/-1!sort
w file.sorted
q
%





share|improve this answer

































    6


















    $ awk 'BEGIN OFS="t"; s=0 /^[^[:blank:]]/ print ++s "b", $0; next print s, $0 ' file | sort -n | cut -f 2-
    0ce Handle Bars
    0cf Front Brake
    0d0 Rear Brake
    HUT 03 VR Controls
    000 Unidentified
    001 Belt
    002 Body Suit
    003 Flexor
    004 Glove
    005 Head Tracker
    006 Head Mounted Display
    007 Hand Tracker
    008 Oculometer
    009 Vest
    00a Animatronic Device
    020 Stereo Enable
    021 Display Enable
    HUT 04 Sport Controls
    000 Unidentified
    001 Baseball Bat
    002 Golf Club


    This uses awk to add a number (and a tab separator) in front of each line corresponding to the section that this line is in. For section headers, we add a number followed by a backspace character (only because backspace sorts before tabs). Then we simply sort the resulting data on these numbers before removing them and the added tab separators.



    Section headers are detected by looking for non-blank characters at the start of the line.






    share|improve this answer























    • 1





      Nice! I especially like the backspace trick.

      – Stephen Kitt
      May 16 at 8:28






    • 1





      With this approach you could also use the section number (after the HUT field) as the prefix, to sort the sections too.

      – Stephen Kitt
      May 16 at 9:20


















    3


















    You could get awk and sort to cooperate to get the job done.



    awk '
    /^[[:blank:]]/print
    close("sort"); print;
    ENDclose("sort")
    ' file


    • Pipe each content line into sort

    • Call close on sort when a section marker is encountered; this causes sort to flush its output to standard output and exit

    • Print the section marker

    • A new instance of sort takes over for the content lines following the section marker

    • Call close on sort at the end to take care of trailing content





    share|improve this answer



































      1


















      For such tasks I often find it tedious to write a script. If it only needs to be done once and maybe for a few files, it can be done quite nicely using a macro if you open the file in vim and type:




      • GoFAKE SECTION<ESC>: add a fake section in the end, and make sure this is at the start of the line (you may have cindent or autoindent enabled). This is required for sorting the last section as well.


      • gg: back go to the start of the file, then the file starts with a section go down one line with j


      • qq: start recording a macro to register q


      • v: start selection


      • /^S+<Enter>: search for the start of the next section


      • k: up one line


      • :!sort<Enter: sort the section


      • nj: go to the first element of the next section


      • q: stop recording the macro


      • @q: repeat the macro


      • 100@@: repeat the macro a few times (until no sections left)


      • dd: delete the last line of the file (the FAKE SECTION)

      You may want to :set lazyredraw to speed up macro execution.






      share|improve this answer



























        Your Answer








        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "106"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: false,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: null,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );














        draft saved

        draft discarded
















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f519203%2fsort-a-section-of-a-file%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown


























        5 Answers
        5






        active

        oldest

        votes








        5 Answers
        5






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        7


















        In Python:



        #!/usr/bin/python3

        with open("file.txt", "r") as ins:
        lines = []
        for line in ins:
        if line.startswith((" ", "t")):
        lines.append(line)
        else:
        lines.sort()
        print(*lines, end = "", sep = "")
        print(line, end = "")
        lines = []
        lines.sort()
        print(*lines, end = "", sep = "")


        This sorts all the sections (separately), not only those between two specific lines.






        share|improve this answer


























        • Superb! This is masterstroke.

          – SHW
          May 16 at 8:01















        7


















        In Python:



        #!/usr/bin/python3

        with open("file.txt", "r") as ins:
        lines = []
        for line in ins:
        if line.startswith((" ", "t")):
        lines.append(line)
        else:
        lines.sort()
        print(*lines, end = "", sep = "")
        print(line, end = "")
        lines = []
        lines.sort()
        print(*lines, end = "", sep = "")


        This sorts all the sections (separately), not only those between two specific lines.






        share|improve this answer


























        • Superb! This is masterstroke.

          – SHW
          May 16 at 8:01













        7














        7










        7









        In Python:



        #!/usr/bin/python3

        with open("file.txt", "r") as ins:
        lines = []
        for line in ins:
        if line.startswith((" ", "t")):
        lines.append(line)
        else:
        lines.sort()
        print(*lines, end = "", sep = "")
        print(line, end = "")
        lines = []
        lines.sort()
        print(*lines, end = "", sep = "")


        This sorts all the sections (separately), not only those between two specific lines.






        share|improve this answer














        In Python:



        #!/usr/bin/python3

        with open("file.txt", "r") as ins:
        lines = []
        for line in ins:
        if line.startswith((" ", "t")):
        lines.append(line)
        else:
        lines.sort()
        print(*lines, end = "", sep = "")
        print(line, end = "")
        lines = []
        lines.sort()
        print(*lines, end = "", sep = "")


        This sorts all the sections (separately), not only those between two specific lines.







        share|improve this answer













        share|improve this answer




        share|improve this answer










        answered May 16 at 7:56









        Stephen KittStephen Kitt

        208k27 gold badges495 silver badges559 bronze badges




        208k27 gold badges495 silver badges559 bronze badges















        • Superb! This is masterstroke.

          – SHW
          May 16 at 8:01

















        • Superb! This is masterstroke.

          – SHW
          May 16 at 8:01
















        Superb! This is masterstroke.

        – SHW
        May 16 at 8:01





        Superb! This is masterstroke.

        – SHW
        May 16 at 8:01













        6


















        For the fun, here is a way to sort a single section using ex:



        ex file <<%
        /HUT
        +1,/HUT/-1!sort
        w file.sorted
        q
        %





        share|improve this answer






























          6


















          For the fun, here is a way to sort a single section using ex:



          ex file <<%
          /HUT
          +1,/HUT/-1!sort
          w file.sorted
          q
          %





          share|improve this answer




























            6














            6










            6









            For the fun, here is a way to sort a single section using ex:



            ex file <<%
            /HUT
            +1,/HUT/-1!sort
            w file.sorted
            q
            %





            share|improve this answer














            For the fun, here is a way to sort a single section using ex:



            ex file <<%
            /HUT
            +1,/HUT/-1!sort
            w file.sorted
            q
            %






            share|improve this answer













            share|improve this answer




            share|improve this answer










            answered May 16 at 8:13









            jlliagrejlliagre

            49.7k9 gold badges91 silver badges142 bronze badges




            49.7k9 gold badges91 silver badges142 bronze badges
























                6


















                $ awk 'BEGIN OFS="t"; s=0 /^[^[:blank:]]/ print ++s "b", $0; next print s, $0 ' file | sort -n | cut -f 2-
                0ce Handle Bars
                0cf Front Brake
                0d0 Rear Brake
                HUT 03 VR Controls
                000 Unidentified
                001 Belt
                002 Body Suit
                003 Flexor
                004 Glove
                005 Head Tracker
                006 Head Mounted Display
                007 Hand Tracker
                008 Oculometer
                009 Vest
                00a Animatronic Device
                020 Stereo Enable
                021 Display Enable
                HUT 04 Sport Controls
                000 Unidentified
                001 Baseball Bat
                002 Golf Club


                This uses awk to add a number (and a tab separator) in front of each line corresponding to the section that this line is in. For section headers, we add a number followed by a backspace character (only because backspace sorts before tabs). Then we simply sort the resulting data on these numbers before removing them and the added tab separators.



                Section headers are detected by looking for non-blank characters at the start of the line.






                share|improve this answer























                • 1





                  Nice! I especially like the backspace trick.

                  – Stephen Kitt
                  May 16 at 8:28






                • 1





                  With this approach you could also use the section number (after the HUT field) as the prefix, to sort the sections too.

                  – Stephen Kitt
                  May 16 at 9:20















                6


















                $ awk 'BEGIN OFS="t"; s=0 /^[^[:blank:]]/ print ++s "b", $0; next print s, $0 ' file | sort -n | cut -f 2-
                0ce Handle Bars
                0cf Front Brake
                0d0 Rear Brake
                HUT 03 VR Controls
                000 Unidentified
                001 Belt
                002 Body Suit
                003 Flexor
                004 Glove
                005 Head Tracker
                006 Head Mounted Display
                007 Hand Tracker
                008 Oculometer
                009 Vest
                00a Animatronic Device
                020 Stereo Enable
                021 Display Enable
                HUT 04 Sport Controls
                000 Unidentified
                001 Baseball Bat
                002 Golf Club


                This uses awk to add a number (and a tab separator) in front of each line corresponding to the section that this line is in. For section headers, we add a number followed by a backspace character (only because backspace sorts before tabs). Then we simply sort the resulting data on these numbers before removing them and the added tab separators.



                Section headers are detected by looking for non-blank characters at the start of the line.






                share|improve this answer























                • 1





                  Nice! I especially like the backspace trick.

                  – Stephen Kitt
                  May 16 at 8:28






                • 1





                  With this approach you could also use the section number (after the HUT field) as the prefix, to sort the sections too.

                  – Stephen Kitt
                  May 16 at 9:20













                6














                6










                6









                $ awk 'BEGIN OFS="t"; s=0 /^[^[:blank:]]/ print ++s "b", $0; next print s, $0 ' file | sort -n | cut -f 2-
                0ce Handle Bars
                0cf Front Brake
                0d0 Rear Brake
                HUT 03 VR Controls
                000 Unidentified
                001 Belt
                002 Body Suit
                003 Flexor
                004 Glove
                005 Head Tracker
                006 Head Mounted Display
                007 Hand Tracker
                008 Oculometer
                009 Vest
                00a Animatronic Device
                020 Stereo Enable
                021 Display Enable
                HUT 04 Sport Controls
                000 Unidentified
                001 Baseball Bat
                002 Golf Club


                This uses awk to add a number (and a tab separator) in front of each line corresponding to the section that this line is in. For section headers, we add a number followed by a backspace character (only because backspace sorts before tabs). Then we simply sort the resulting data on these numbers before removing them and the added tab separators.



                Section headers are detected by looking for non-blank characters at the start of the line.






                share|improve this answer
















                $ awk 'BEGIN OFS="t"; s=0 /^[^[:blank:]]/ print ++s "b", $0; next print s, $0 ' file | sort -n | cut -f 2-
                0ce Handle Bars
                0cf Front Brake
                0d0 Rear Brake
                HUT 03 VR Controls
                000 Unidentified
                001 Belt
                002 Body Suit
                003 Flexor
                004 Glove
                005 Head Tracker
                006 Head Mounted Display
                007 Hand Tracker
                008 Oculometer
                009 Vest
                00a Animatronic Device
                020 Stereo Enable
                021 Display Enable
                HUT 04 Sport Controls
                000 Unidentified
                001 Baseball Bat
                002 Golf Club


                This uses awk to add a number (and a tab separator) in front of each line corresponding to the section that this line is in. For section headers, we add a number followed by a backspace character (only because backspace sorts before tabs). Then we simply sort the resulting data on these numbers before removing them and the added tab separators.



                Section headers are detected by looking for non-blank characters at the start of the line.







                share|improve this answer















                share|improve this answer




                share|improve this answer








                edited May 16 at 8:28

























                answered May 16 at 8:26









                KusalanandaKusalananda

                168k20 gold badges326 silver badges522 bronze badges




                168k20 gold badges326 silver badges522 bronze badges










                • 1





                  Nice! I especially like the backspace trick.

                  – Stephen Kitt
                  May 16 at 8:28






                • 1





                  With this approach you could also use the section number (after the HUT field) as the prefix, to sort the sections too.

                  – Stephen Kitt
                  May 16 at 9:20












                • 1





                  Nice! I especially like the backspace trick.

                  – Stephen Kitt
                  May 16 at 8:28






                • 1





                  With this approach you could also use the section number (after the HUT field) as the prefix, to sort the sections too.

                  – Stephen Kitt
                  May 16 at 9:20







                1




                1





                Nice! I especially like the backspace trick.

                – Stephen Kitt
                May 16 at 8:28





                Nice! I especially like the backspace trick.

                – Stephen Kitt
                May 16 at 8:28




                1




                1





                With this approach you could also use the section number (after the HUT field) as the prefix, to sort the sections too.

                – Stephen Kitt
                May 16 at 9:20





                With this approach you could also use the section number (after the HUT field) as the prefix, to sort the sections too.

                – Stephen Kitt
                May 16 at 9:20











                3


















                You could get awk and sort to cooperate to get the job done.



                awk '
                /^[[:blank:]]/print
                close("sort"); print;
                ENDclose("sort")
                ' file


                • Pipe each content line into sort

                • Call close on sort when a section marker is encountered; this causes sort to flush its output to standard output and exit

                • Print the section marker

                • A new instance of sort takes over for the content lines following the section marker

                • Call close on sort at the end to take care of trailing content





                share|improve this answer
































                  3


















                  You could get awk and sort to cooperate to get the job done.



                  awk '
                  /^[[:blank:]]/print
                  close("sort"); print;
                  ENDclose("sort")
                  ' file


                  • Pipe each content line into sort

                  • Call close on sort when a section marker is encountered; this causes sort to flush its output to standard output and exit

                  • Print the section marker

                  • A new instance of sort takes over for the content lines following the section marker

                  • Call close on sort at the end to take care of trailing content





                  share|improve this answer






























                    3














                    3










                    3









                    You could get awk and sort to cooperate to get the job done.



                    awk '
                    /^[[:blank:]]/print
                    close("sort"); print;
                    ENDclose("sort")
                    ' file


                    • Pipe each content line into sort

                    • Call close on sort when a section marker is encountered; this causes sort to flush its output to standard output and exit

                    • Print the section marker

                    • A new instance of sort takes over for the content lines following the section marker

                    • Call close on sort at the end to take care of trailing content





                    share|improve this answer
















                    You could get awk and sort to cooperate to get the job done.



                    awk '
                    /^[[:blank:]]/print
                    close("sort"); print;
                    ENDclose("sort")
                    ' file


                    • Pipe each content line into sort

                    • Call close on sort when a section marker is encountered; this causes sort to flush its output to standard output and exit

                    • Print the section marker

                    • A new instance of sort takes over for the content lines following the section marker

                    • Call close on sort at the end to take care of trailing content






                    share|improve this answer















                    share|improve this answer




                    share|improve this answer








                    edited May 16 at 22:28

























                    answered May 16 at 17:12









                    iruvariruvar

                    13.1k6 gold badges34 silver badges64 bronze badges




                    13.1k6 gold badges34 silver badges64 bronze badges
























                        1


















                        For such tasks I often find it tedious to write a script. If it only needs to be done once and maybe for a few files, it can be done quite nicely using a macro if you open the file in vim and type:




                        • GoFAKE SECTION<ESC>: add a fake section in the end, and make sure this is at the start of the line (you may have cindent or autoindent enabled). This is required for sorting the last section as well.


                        • gg: back go to the start of the file, then the file starts with a section go down one line with j


                        • qq: start recording a macro to register q


                        • v: start selection


                        • /^S+<Enter>: search for the start of the next section


                        • k: up one line


                        • :!sort<Enter: sort the section


                        • nj: go to the first element of the next section


                        • q: stop recording the macro


                        • @q: repeat the macro


                        • 100@@: repeat the macro a few times (until no sections left)


                        • dd: delete the last line of the file (the FAKE SECTION)

                        You may want to :set lazyredraw to speed up macro execution.






                        share|improve this answer






























                          1


















                          For such tasks I often find it tedious to write a script. If it only needs to be done once and maybe for a few files, it can be done quite nicely using a macro if you open the file in vim and type:




                          • GoFAKE SECTION<ESC>: add a fake section in the end, and make sure this is at the start of the line (you may have cindent or autoindent enabled). This is required for sorting the last section as well.


                          • gg: back go to the start of the file, then the file starts with a section go down one line with j


                          • qq: start recording a macro to register q


                          • v: start selection


                          • /^S+<Enter>: search for the start of the next section


                          • k: up one line


                          • :!sort<Enter: sort the section


                          • nj: go to the first element of the next section


                          • q: stop recording the macro


                          • @q: repeat the macro


                          • 100@@: repeat the macro a few times (until no sections left)


                          • dd: delete the last line of the file (the FAKE SECTION)

                          You may want to :set lazyredraw to speed up macro execution.






                          share|improve this answer




























                            1














                            1










                            1









                            For such tasks I often find it tedious to write a script. If it only needs to be done once and maybe for a few files, it can be done quite nicely using a macro if you open the file in vim and type:




                            • GoFAKE SECTION<ESC>: add a fake section in the end, and make sure this is at the start of the line (you may have cindent or autoindent enabled). This is required for sorting the last section as well.


                            • gg: back go to the start of the file, then the file starts with a section go down one line with j


                            • qq: start recording a macro to register q


                            • v: start selection


                            • /^S+<Enter>: search for the start of the next section


                            • k: up one line


                            • :!sort<Enter: sort the section


                            • nj: go to the first element of the next section


                            • q: stop recording the macro


                            • @q: repeat the macro


                            • 100@@: repeat the macro a few times (until no sections left)


                            • dd: delete the last line of the file (the FAKE SECTION)

                            You may want to :set lazyredraw to speed up macro execution.






                            share|improve this answer














                            For such tasks I often find it tedious to write a script. If it only needs to be done once and maybe for a few files, it can be done quite nicely using a macro if you open the file in vim and type:




                            • GoFAKE SECTION<ESC>: add a fake section in the end, and make sure this is at the start of the line (you may have cindent or autoindent enabled). This is required for sorting the last section as well.


                            • gg: back go to the start of the file, then the file starts with a section go down one line with j


                            • qq: start recording a macro to register q


                            • v: start selection


                            • /^S+<Enter>: search for the start of the next section


                            • k: up one line


                            • :!sort<Enter: sort the section


                            • nj: go to the first element of the next section


                            • q: stop recording the macro


                            • @q: repeat the macro


                            • 100@@: repeat the macro a few times (until no sections left)


                            • dd: delete the last line of the file (the FAKE SECTION)

                            You may want to :set lazyredraw to speed up macro execution.







                            share|improve this answer













                            share|improve this answer




                            share|improve this answer










                            answered May 16 at 22:15









                            MarcDefiantMarcDefiant

                            1113 bronze badges




                            1113 bronze badges































                                draft saved

                                draft discarded















































                                Thanks for contributing an answer to Unix & Linux Stack Exchange!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f519203%2fsort-a-section-of-a-file%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown









                                Popular posts from this blog

                                Distance measures on a map of a game The 2019 Stack Overflow Developer Survey Results Are Inmin distance in a graphShortest distance path on contour plotHow to plot a tilted map?Finding points outside of a diskDelaunay link distanceAnnulus from GeoDisks: drawing a ring on a mapNegative Correlation DistanceFind distance along a path (GPS coordinates)Finding position at given distance in a GeoPathMathematics behind distance estimation using camera

                                How to get a smooth, uniform ParametricPlot of a 2D Region?How to plot a complicated Region?How to exclude a region from ParametricPlotHow discretize a region placing vertices on a specific non-uniform gridHow to transform a Plot or a ParametricPlot into a RegionHow can I get a smooth plot of a bounded region?Smooth ParametricPlot3D with RegionFunction?Smooth border of a region ParametricPlotSmooth region boundarySmooth region plot from list of pointsGet minimum y of a certain x in a region

                                Genealogie vun de Merowenger Vum Merowech bis zum Chilperich I. | Navigatiounsmenü