How can I remove lines under a sub heading in a file using linux commandsHow to remove multiple blank lines...

Is the first of the 10 Commandments considered a mitzvah?

What is Gilligan's full name?

Is it good practice to create tables dynamically?

Idiom for 'person who gets violent when drunk"

I am caught when I was about to steal some candies

If absolute velocity does not exist, how can we say a rocket accelerates in empty space?

Harley Davidson clattering noise from engine, backfire and failure to start

What do I need to do, tax-wise, for a sudden windfall?

Jam with honey & without pectin has a saucy consistency always

Placement of positioning lights on A320 winglets

What is the source of 'Ma'alin bekodesh'?

Do Veracrypt encrypted volumes have any kind of brute force protection?

Is it possible to have battery technology that can't be duplicated?

Realistic, logical way for men with medieval-era weaponry to compete with much larger and physically stronger foes

Why would a home insurer offer a discount based on credit score?

Do they make "karaoke" versions of concertos for solo practice?

Why are backslashes included in this shell script?

A team managed by my peer is close to melting down

Can you open the door or die? v2

Why do (or did, until very recently) aircraft transponders wait to be interrogated before broadcasting beacon signals?

Is it a good security practice to force employees hide their employer to avoid being targeted?

Why didn't all the iron and heavier elements find their way to the center of the accretion disc in the early solar system?

What did the 8086 (and 8088) do upon encountering an illegal instruction?

Can a 40amp breaker be used safely and without issue with a 40amp device on 6AWG wire?



How can I remove lines under a sub heading in a file using linux commands


How to remove multiple blank lines from a file?sed remove last space only on end of line,combined with awkDelete lines between 2 strings in SolarisTo remove newlines after empty lineRemove spaces in file under certain criteriaSelecting text from a file removing unwanted text using shellHow to insert the lines from a file into another file after a key word?Linux - Identify a multi-pattern in a set of lines and replaceIs there a another way to display a part of a line using sedsed replace matching line which does not start with #






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







3















I have a file as below . In which I want to remove lines under a particular sub heading alone. I tried using some sed and awk commands but I couldn't get it. Can any one help to crack this with some linux commands.



[first attempt]
a=10
b=20

[second attempt]
a=20
b=20

[third attempt ]
a=30
b=50


I want to remove lines under '[second attempt]' sub heading alone. The output should be as below. I just want to remove the contents under the sub heading and optionally the removed lines can be replaced by one blank line



[first attempt]
a=10
b=20

[second attempt]

[third attempt ]
a=30
b=50









share|improve this question




















  • 1





    Why are there two line breaks in the second version? Do you always want two line breaks, or does this depend on the number of empty lines in the original version?

    – Sparhawk
    Oct 22 '15 at 5:36






  • 1





    It would appear that you have accidentally created two accounts.  You should use the contact form and select “I need to merge user profiles” to have your accounts merged.  In order to merge them, you will need to provide links to the two accounts.  For your information, these are unix.stackexchange.com/users/139641/viju-m and unix.stackexchange.com/users/139642/viju.  You’ll then be able to edit, comment on and accept answers to this question.

    – G-Man
    Oct 22 '15 at 6:29











  • The question has been exactly reversed. I was going to roll it back but then I saw this edit is apparently by the OP as his second identity. However, the answers below have all been made invalid by the edit as the question is completely different. EDIT: Actually I see Gilles voted to reject the edit. I agree with him; it is a destructive edit.

    – Wildcard
    Oct 26 '15 at 6:17













  • @Viju, I have reversed your edit. Please post a separate question instead of completely changing what you've asked. You also seem to have created two accounts, please see [here](unix.stackexchange.com/help/merging-accounts) for how to merge them.

    – terdon
    Oct 26 '15 at 12:16


















3















I have a file as below . In which I want to remove lines under a particular sub heading alone. I tried using some sed and awk commands but I couldn't get it. Can any one help to crack this with some linux commands.



[first attempt]
a=10
b=20

[second attempt]
a=20
b=20

[third attempt ]
a=30
b=50


I want to remove lines under '[second attempt]' sub heading alone. The output should be as below. I just want to remove the contents under the sub heading and optionally the removed lines can be replaced by one blank line



[first attempt]
a=10
b=20

[second attempt]

[third attempt ]
a=30
b=50









share|improve this question




















  • 1





    Why are there two line breaks in the second version? Do you always want two line breaks, or does this depend on the number of empty lines in the original version?

    – Sparhawk
    Oct 22 '15 at 5:36






  • 1





    It would appear that you have accidentally created two accounts.  You should use the contact form and select “I need to merge user profiles” to have your accounts merged.  In order to merge them, you will need to provide links to the two accounts.  For your information, these are unix.stackexchange.com/users/139641/viju-m and unix.stackexchange.com/users/139642/viju.  You’ll then be able to edit, comment on and accept answers to this question.

    – G-Man
    Oct 22 '15 at 6:29











  • The question has been exactly reversed. I was going to roll it back but then I saw this edit is apparently by the OP as his second identity. However, the answers below have all been made invalid by the edit as the question is completely different. EDIT: Actually I see Gilles voted to reject the edit. I agree with him; it is a destructive edit.

    – Wildcard
    Oct 26 '15 at 6:17













  • @Viju, I have reversed your edit. Please post a separate question instead of completely changing what you've asked. You also seem to have created two accounts, please see [here](unix.stackexchange.com/help/merging-accounts) for how to merge them.

    – terdon
    Oct 26 '15 at 12:16














3












3








3








I have a file as below . In which I want to remove lines under a particular sub heading alone. I tried using some sed and awk commands but I couldn't get it. Can any one help to crack this with some linux commands.



[first attempt]
a=10
b=20

[second attempt]
a=20
b=20

[third attempt ]
a=30
b=50


I want to remove lines under '[second attempt]' sub heading alone. The output should be as below. I just want to remove the contents under the sub heading and optionally the removed lines can be replaced by one blank line



[first attempt]
a=10
b=20

[second attempt]

[third attempt ]
a=30
b=50









share|improve this question
















I have a file as below . In which I want to remove lines under a particular sub heading alone. I tried using some sed and awk commands but I couldn't get it. Can any one help to crack this with some linux commands.



[first attempt]
a=10
b=20

[second attempt]
a=20
b=20

[third attempt ]
a=30
b=50


I want to remove lines under '[second attempt]' sub heading alone. The output should be as below. I just want to remove the contents under the sub heading and optionally the removed lines can be replaced by one blank line



[first attempt]
a=10
b=20

[second attempt]

[third attempt ]
a=30
b=50






text-processing sed awk






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Oct 26 '15 at 12:15









terdon

137k33276458




137k33276458










asked Oct 22 '15 at 5:33









Viju MViju M

161




161








  • 1





    Why are there two line breaks in the second version? Do you always want two line breaks, or does this depend on the number of empty lines in the original version?

    – Sparhawk
    Oct 22 '15 at 5:36






  • 1





    It would appear that you have accidentally created two accounts.  You should use the contact form and select “I need to merge user profiles” to have your accounts merged.  In order to merge them, you will need to provide links to the two accounts.  For your information, these are unix.stackexchange.com/users/139641/viju-m and unix.stackexchange.com/users/139642/viju.  You’ll then be able to edit, comment on and accept answers to this question.

    – G-Man
    Oct 22 '15 at 6:29











  • The question has been exactly reversed. I was going to roll it back but then I saw this edit is apparently by the OP as his second identity. However, the answers below have all been made invalid by the edit as the question is completely different. EDIT: Actually I see Gilles voted to reject the edit. I agree with him; it is a destructive edit.

    – Wildcard
    Oct 26 '15 at 6:17













  • @Viju, I have reversed your edit. Please post a separate question instead of completely changing what you've asked. You also seem to have created two accounts, please see [here](unix.stackexchange.com/help/merging-accounts) for how to merge them.

    – terdon
    Oct 26 '15 at 12:16














  • 1





    Why are there two line breaks in the second version? Do you always want two line breaks, or does this depend on the number of empty lines in the original version?

    – Sparhawk
    Oct 22 '15 at 5:36






  • 1





    It would appear that you have accidentally created two accounts.  You should use the contact form and select “I need to merge user profiles” to have your accounts merged.  In order to merge them, you will need to provide links to the two accounts.  For your information, these are unix.stackexchange.com/users/139641/viju-m and unix.stackexchange.com/users/139642/viju.  You’ll then be able to edit, comment on and accept answers to this question.

    – G-Man
    Oct 22 '15 at 6:29











  • The question has been exactly reversed. I was going to roll it back but then I saw this edit is apparently by the OP as his second identity. However, the answers below have all been made invalid by the edit as the question is completely different. EDIT: Actually I see Gilles voted to reject the edit. I agree with him; it is a destructive edit.

    – Wildcard
    Oct 26 '15 at 6:17













  • @Viju, I have reversed your edit. Please post a separate question instead of completely changing what you've asked. You also seem to have created two accounts, please see [here](unix.stackexchange.com/help/merging-accounts) for how to merge them.

    – terdon
    Oct 26 '15 at 12:16








1




1





Why are there two line breaks in the second version? Do you always want two line breaks, or does this depend on the number of empty lines in the original version?

– Sparhawk
Oct 22 '15 at 5:36





Why are there two line breaks in the second version? Do you always want two line breaks, or does this depend on the number of empty lines in the original version?

– Sparhawk
Oct 22 '15 at 5:36




1




1





It would appear that you have accidentally created two accounts.  You should use the contact form and select “I need to merge user profiles” to have your accounts merged.  In order to merge them, you will need to provide links to the two accounts.  For your information, these are unix.stackexchange.com/users/139641/viju-m and unix.stackexchange.com/users/139642/viju.  You’ll then be able to edit, comment on and accept answers to this question.

– G-Man
Oct 22 '15 at 6:29





It would appear that you have accidentally created two accounts.  You should use the contact form and select “I need to merge user profiles” to have your accounts merged.  In order to merge them, you will need to provide links to the two accounts.  For your information, these are unix.stackexchange.com/users/139641/viju-m and unix.stackexchange.com/users/139642/viju.  You’ll then be able to edit, comment on and accept answers to this question.

– G-Man
Oct 22 '15 at 6:29













The question has been exactly reversed. I was going to roll it back but then I saw this edit is apparently by the OP as his second identity. However, the answers below have all been made invalid by the edit as the question is completely different. EDIT: Actually I see Gilles voted to reject the edit. I agree with him; it is a destructive edit.

– Wildcard
Oct 26 '15 at 6:17







The question has been exactly reversed. I was going to roll it back but then I saw this edit is apparently by the OP as his second identity. However, the answers below have all been made invalid by the edit as the question is completely different. EDIT: Actually I see Gilles voted to reject the edit. I agree with him; it is a destructive edit.

– Wildcard
Oct 26 '15 at 6:17















@Viju, I have reversed your edit. Please post a separate question instead of completely changing what you've asked. You also seem to have created two accounts, please see [here](unix.stackexchange.com/help/merging-accounts) for how to merge them.

– terdon
Oct 26 '15 at 12:16





@Viju, I have reversed your edit. Please post a separate question instead of completely changing what you've asked. You also seem to have created two accounts, please see [here](unix.stackexchange.com/help/merging-accounts) for how to merge them.

– terdon
Oct 26 '15 at 12:16










4 Answers
4






active

oldest

votes


















1














awk -v blkid=0 -v rmblk=2 '{
if ( $1 ~ /^[/) {
blkid+=1;blkn=NR;print };
if ( blkid !=rmblk && NR!=blkn )
print ;
else if(blkid ==rmblk && NF == 0)
print ""}' file.txt


Each block will have id starting from 1 increment by one for each block: blkid.



The block id of the block you want remove : rmblk



Each block will start when first field starts with [.



The variable blkn stores the NR value of [first attempt] [second attempt] etc..






share|improve this answer

































    1














    sed '$!N;/^[second/,/^n[/P;D' <infile >outfile


    That should probably do, though I'm not perfectly clear about what you want to do with the trailing blank line that immediately precedes the next section. This output includes it, because it seems the right thing to do, but if you want to drop only that one last blank line from any section that can be done relatively easily - so just ask.



    Basically, for every input line which is ! not the $ last, sed also pulls in the Next line and appends it to pattern space following an inserted newline character delimiter. Each time this happens the pattern space shifts:



     ^Line1nLine2$
    ^Line2nLine3$
    ^Line3nLine4$


    If the current pattern space matches the patterns ^[second or ^n[ or any line which occurs between those two, sed will Print up to the first occurring newline in pattern space - and so it only prints half of its buffer for each iteration.



    Last, sed Deletes up to the first occurring newline in pattern space and starts the script again from the top - which is how we get the shifting effect. This is known as a sliding window. It works very well, and is quite fast.





    I guess there are multiple versions of this question or something? Whatever the case, going the opposite way is not so difficult to do, really.



    You might do it like...



    sed -ne '/^[[^s]/,/^[s/p' <in >out


    Which would just print any content which doesn't follow a header beginning with an s character, and and all headers regardless. It doesn't do the neat little newline after, though:





    [first attempt]
    a=10
    b=20

    [second attempt]
    [third attempt ]
    a=30
    b=50


    If you want to get a little more explicit you can do that too:



    sed '/^[[second]/P;$!N;//,/n$/!P;D' <in >out


    ...which does do the neat little newline...



    [first attempt]
    a=10
    b=20

    [second attempt]

    [third attempt ]
    a=30
    b=50


    All of these are sed ranges, and for each match expression that looks like:



    /match1/,/match2/command


    ...sed will apply the command to both matched lines and all lines that come between.






    share|improve this answer


























    • You may want to change this as it was an answer to the inverted form of the question—an edit which has since been rolled back.

      – Wildcard
      Oct 27 '15 at 6:07



















    0














    You can also do this with a short sed script. Put the following in a file:



    /second/ {
    n
    : del
    /./ ! b
    N
    s/.*n//
    b del
    }


    Call it script. Then use sed -f script myfile. If you are trying to edit the file in place, use sed -i -f script myfile, but I recommend running the first command before you try that and make sure it's exactly the output you want.



    Explanation:



    Once the string second is found, sed will look at the next line. If that line is not empty, it is discarded and the next line in the file is looked at until an empty line is found. That empty line and all other lines in the file are printed. (Unless there is another line containing the string second, in which case the process repeats.)



    (I can explain more if anyone is interested.)






    share|improve this answer































      0














      I'll try to grep to the two line numbers of "second attempt" and "third attempt" then delete whatever is in between. Edit accordingly to your needs. :)



      #getting line number for [second attempt]
      line_num_second=$(grep -n "second attempt" yourfile.txt | cut -d : -f 1)

      #getting line number for [third attempt]
      line_num_third=$(grep -n "third attempt" yourfile.txt | cut -d : -f 1)

      start=$(expr $line_num_second +1)
      end=$(expr $line_num_third -2)

      #removes the content in between [second attempt] and [third attempt]
      sed $start,"$end"d yourfile.txt

      # sed -i $start,"$end"d yourfile.txt # -i - overwite/edit your files in-place instead of printing to standard output





      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/3.0/"u003ecc by-sa 3.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%2f237822%2fhow-can-i-remove-lines-under-a-sub-heading-in-a-file-using-linux-commands%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1














        awk -v blkid=0 -v rmblk=2 '{
        if ( $1 ~ /^[/) {
        blkid+=1;blkn=NR;print };
        if ( blkid !=rmblk && NR!=blkn )
        print ;
        else if(blkid ==rmblk && NF == 0)
        print ""}' file.txt


        Each block will have id starting from 1 increment by one for each block: blkid.



        The block id of the block you want remove : rmblk



        Each block will start when first field starts with [.



        The variable blkn stores the NR value of [first attempt] [second attempt] etc..






        share|improve this answer






























          1














          awk -v blkid=0 -v rmblk=2 '{
          if ( $1 ~ /^[/) {
          blkid+=1;blkn=NR;print };
          if ( blkid !=rmblk && NR!=blkn )
          print ;
          else if(blkid ==rmblk && NF == 0)
          print ""}' file.txt


          Each block will have id starting from 1 increment by one for each block: blkid.



          The block id of the block you want remove : rmblk



          Each block will start when first field starts with [.



          The variable blkn stores the NR value of [first attempt] [second attempt] etc..






          share|improve this answer




























            1












            1








            1







            awk -v blkid=0 -v rmblk=2 '{
            if ( $1 ~ /^[/) {
            blkid+=1;blkn=NR;print };
            if ( blkid !=rmblk && NR!=blkn )
            print ;
            else if(blkid ==rmblk && NF == 0)
            print ""}' file.txt


            Each block will have id starting from 1 increment by one for each block: blkid.



            The block id of the block you want remove : rmblk



            Each block will start when first field starts with [.



            The variable blkn stores the NR value of [first attempt] [second attempt] etc..






            share|improve this answer















            awk -v blkid=0 -v rmblk=2 '{
            if ( $1 ~ /^[/) {
            blkid+=1;blkn=NR;print };
            if ( blkid !=rmblk && NR!=blkn )
            print ;
            else if(blkid ==rmblk && NF == 0)
            print ""}' file.txt


            Each block will have id starting from 1 increment by one for each block: blkid.



            The block id of the block you want remove : rmblk



            Each block will start when first field starts with [.



            The variable blkn stores the NR value of [first attempt] [second attempt] etc..







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Oct 22 '15 at 10:00

























            answered Oct 22 '15 at 9:07









            7171u7171u

            89549




            89549

























                1














                sed '$!N;/^[second/,/^n[/P;D' <infile >outfile


                That should probably do, though I'm not perfectly clear about what you want to do with the trailing blank line that immediately precedes the next section. This output includes it, because it seems the right thing to do, but if you want to drop only that one last blank line from any section that can be done relatively easily - so just ask.



                Basically, for every input line which is ! not the $ last, sed also pulls in the Next line and appends it to pattern space following an inserted newline character delimiter. Each time this happens the pattern space shifts:



                 ^Line1nLine2$
                ^Line2nLine3$
                ^Line3nLine4$


                If the current pattern space matches the patterns ^[second or ^n[ or any line which occurs between those two, sed will Print up to the first occurring newline in pattern space - and so it only prints half of its buffer for each iteration.



                Last, sed Deletes up to the first occurring newline in pattern space and starts the script again from the top - which is how we get the shifting effect. This is known as a sliding window. It works very well, and is quite fast.





                I guess there are multiple versions of this question or something? Whatever the case, going the opposite way is not so difficult to do, really.



                You might do it like...



                sed -ne '/^[[^s]/,/^[s/p' <in >out


                Which would just print any content which doesn't follow a header beginning with an s character, and and all headers regardless. It doesn't do the neat little newline after, though:





                [first attempt]
                a=10
                b=20

                [second attempt]
                [third attempt ]
                a=30
                b=50


                If you want to get a little more explicit you can do that too:



                sed '/^[[second]/P;$!N;//,/n$/!P;D' <in >out


                ...which does do the neat little newline...



                [first attempt]
                a=10
                b=20

                [second attempt]

                [third attempt ]
                a=30
                b=50


                All of these are sed ranges, and for each match expression that looks like:



                /match1/,/match2/command


                ...sed will apply the command to both matched lines and all lines that come between.






                share|improve this answer


























                • You may want to change this as it was an answer to the inverted form of the question—an edit which has since been rolled back.

                  – Wildcard
                  Oct 27 '15 at 6:07
















                1














                sed '$!N;/^[second/,/^n[/P;D' <infile >outfile


                That should probably do, though I'm not perfectly clear about what you want to do with the trailing blank line that immediately precedes the next section. This output includes it, because it seems the right thing to do, but if you want to drop only that one last blank line from any section that can be done relatively easily - so just ask.



                Basically, for every input line which is ! not the $ last, sed also pulls in the Next line and appends it to pattern space following an inserted newline character delimiter. Each time this happens the pattern space shifts:



                 ^Line1nLine2$
                ^Line2nLine3$
                ^Line3nLine4$


                If the current pattern space matches the patterns ^[second or ^n[ or any line which occurs between those two, sed will Print up to the first occurring newline in pattern space - and so it only prints half of its buffer for each iteration.



                Last, sed Deletes up to the first occurring newline in pattern space and starts the script again from the top - which is how we get the shifting effect. This is known as a sliding window. It works very well, and is quite fast.





                I guess there are multiple versions of this question or something? Whatever the case, going the opposite way is not so difficult to do, really.



                You might do it like...



                sed -ne '/^[[^s]/,/^[s/p' <in >out


                Which would just print any content which doesn't follow a header beginning with an s character, and and all headers regardless. It doesn't do the neat little newline after, though:





                [first attempt]
                a=10
                b=20

                [second attempt]
                [third attempt ]
                a=30
                b=50


                If you want to get a little more explicit you can do that too:



                sed '/^[[second]/P;$!N;//,/n$/!P;D' <in >out


                ...which does do the neat little newline...



                [first attempt]
                a=10
                b=20

                [second attempt]

                [third attempt ]
                a=30
                b=50


                All of these are sed ranges, and for each match expression that looks like:



                /match1/,/match2/command


                ...sed will apply the command to both matched lines and all lines that come between.






                share|improve this answer


























                • You may want to change this as it was an answer to the inverted form of the question—an edit which has since been rolled back.

                  – Wildcard
                  Oct 27 '15 at 6:07














                1












                1








                1







                sed '$!N;/^[second/,/^n[/P;D' <infile >outfile


                That should probably do, though I'm not perfectly clear about what you want to do with the trailing blank line that immediately precedes the next section. This output includes it, because it seems the right thing to do, but if you want to drop only that one last blank line from any section that can be done relatively easily - so just ask.



                Basically, for every input line which is ! not the $ last, sed also pulls in the Next line and appends it to pattern space following an inserted newline character delimiter. Each time this happens the pattern space shifts:



                 ^Line1nLine2$
                ^Line2nLine3$
                ^Line3nLine4$


                If the current pattern space matches the patterns ^[second or ^n[ or any line which occurs between those two, sed will Print up to the first occurring newline in pattern space - and so it only prints half of its buffer for each iteration.



                Last, sed Deletes up to the first occurring newline in pattern space and starts the script again from the top - which is how we get the shifting effect. This is known as a sliding window. It works very well, and is quite fast.





                I guess there are multiple versions of this question or something? Whatever the case, going the opposite way is not so difficult to do, really.



                You might do it like...



                sed -ne '/^[[^s]/,/^[s/p' <in >out


                Which would just print any content which doesn't follow a header beginning with an s character, and and all headers regardless. It doesn't do the neat little newline after, though:





                [first attempt]
                a=10
                b=20

                [second attempt]
                [third attempt ]
                a=30
                b=50


                If you want to get a little more explicit you can do that too:



                sed '/^[[second]/P;$!N;//,/n$/!P;D' <in >out


                ...which does do the neat little newline...



                [first attempt]
                a=10
                b=20

                [second attempt]

                [third attempt ]
                a=30
                b=50


                All of these are sed ranges, and for each match expression that looks like:



                /match1/,/match2/command


                ...sed will apply the command to both matched lines and all lines that come between.






                share|improve this answer















                sed '$!N;/^[second/,/^n[/P;D' <infile >outfile


                That should probably do, though I'm not perfectly clear about what you want to do with the trailing blank line that immediately precedes the next section. This output includes it, because it seems the right thing to do, but if you want to drop only that one last blank line from any section that can be done relatively easily - so just ask.



                Basically, for every input line which is ! not the $ last, sed also pulls in the Next line and appends it to pattern space following an inserted newline character delimiter. Each time this happens the pattern space shifts:



                 ^Line1nLine2$
                ^Line2nLine3$
                ^Line3nLine4$


                If the current pattern space matches the patterns ^[second or ^n[ or any line which occurs between those two, sed will Print up to the first occurring newline in pattern space - and so it only prints half of its buffer for each iteration.



                Last, sed Deletes up to the first occurring newline in pattern space and starts the script again from the top - which is how we get the shifting effect. This is known as a sliding window. It works very well, and is quite fast.





                I guess there are multiple versions of this question or something? Whatever the case, going the opposite way is not so difficult to do, really.



                You might do it like...



                sed -ne '/^[[^s]/,/^[s/p' <in >out


                Which would just print any content which doesn't follow a header beginning with an s character, and and all headers regardless. It doesn't do the neat little newline after, though:





                [first attempt]
                a=10
                b=20

                [second attempt]
                [third attempt ]
                a=30
                b=50


                If you want to get a little more explicit you can do that too:



                sed '/^[[second]/P;$!N;//,/n$/!P;D' <in >out


                ...which does do the neat little newline...



                [first attempt]
                a=10
                b=20

                [second attempt]

                [third attempt ]
                a=30
                b=50


                All of these are sed ranges, and for each match expression that looks like:



                /match1/,/match2/command


                ...sed will apply the command to both matched lines and all lines that come between.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Oct 28 '15 at 3:29

























                answered Oct 26 '15 at 6:04









                mikeservmikeserv

                46.4k669167




                46.4k669167













                • You may want to change this as it was an answer to the inverted form of the question—an edit which has since been rolled back.

                  – Wildcard
                  Oct 27 '15 at 6:07



















                • You may want to change this as it was an answer to the inverted form of the question—an edit which has since been rolled back.

                  – Wildcard
                  Oct 27 '15 at 6:07

















                You may want to change this as it was an answer to the inverted form of the question—an edit which has since been rolled back.

                – Wildcard
                Oct 27 '15 at 6:07





                You may want to change this as it was an answer to the inverted form of the question—an edit which has since been rolled back.

                – Wildcard
                Oct 27 '15 at 6:07











                0














                You can also do this with a short sed script. Put the following in a file:



                /second/ {
                n
                : del
                /./ ! b
                N
                s/.*n//
                b del
                }


                Call it script. Then use sed -f script myfile. If you are trying to edit the file in place, use sed -i -f script myfile, but I recommend running the first command before you try that and make sure it's exactly the output you want.



                Explanation:



                Once the string second is found, sed will look at the next line. If that line is not empty, it is discarded and the next line in the file is looked at until an empty line is found. That empty line and all other lines in the file are printed. (Unless there is another line containing the string second, in which case the process repeats.)



                (I can explain more if anyone is interested.)






                share|improve this answer




























                  0














                  You can also do this with a short sed script. Put the following in a file:



                  /second/ {
                  n
                  : del
                  /./ ! b
                  N
                  s/.*n//
                  b del
                  }


                  Call it script. Then use sed -f script myfile. If you are trying to edit the file in place, use sed -i -f script myfile, but I recommend running the first command before you try that and make sure it's exactly the output you want.



                  Explanation:



                  Once the string second is found, sed will look at the next line. If that line is not empty, it is discarded and the next line in the file is looked at until an empty line is found. That empty line and all other lines in the file are printed. (Unless there is another line containing the string second, in which case the process repeats.)



                  (I can explain more if anyone is interested.)






                  share|improve this answer


























                    0












                    0








                    0







                    You can also do this with a short sed script. Put the following in a file:



                    /second/ {
                    n
                    : del
                    /./ ! b
                    N
                    s/.*n//
                    b del
                    }


                    Call it script. Then use sed -f script myfile. If you are trying to edit the file in place, use sed -i -f script myfile, but I recommend running the first command before you try that and make sure it's exactly the output you want.



                    Explanation:



                    Once the string second is found, sed will look at the next line. If that line is not empty, it is discarded and the next line in the file is looked at until an empty line is found. That empty line and all other lines in the file are printed. (Unless there is another line containing the string second, in which case the process repeats.)



                    (I can explain more if anyone is interested.)






                    share|improve this answer













                    You can also do this with a short sed script. Put the following in a file:



                    /second/ {
                    n
                    : del
                    /./ ! b
                    N
                    s/.*n//
                    b del
                    }


                    Call it script. Then use sed -f script myfile. If you are trying to edit the file in place, use sed -i -f script myfile, but I recommend running the first command before you try that and make sure it's exactly the output you want.



                    Explanation:



                    Once the string second is found, sed will look at the next line. If that line is not empty, it is discarded and the next line in the file is looked at until an empty line is found. That empty line and all other lines in the file are printed. (Unless there is another line containing the string second, in which case the process repeats.)



                    (I can explain more if anyone is interested.)







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Oct 23 '15 at 14:46









                    WildcardWildcard

                    23.6k1068177




                    23.6k1068177























                        0














                        I'll try to grep to the two line numbers of "second attempt" and "third attempt" then delete whatever is in between. Edit accordingly to your needs. :)



                        #getting line number for [second attempt]
                        line_num_second=$(grep -n "second attempt" yourfile.txt | cut -d : -f 1)

                        #getting line number for [third attempt]
                        line_num_third=$(grep -n "third attempt" yourfile.txt | cut -d : -f 1)

                        start=$(expr $line_num_second +1)
                        end=$(expr $line_num_third -2)

                        #removes the content in between [second attempt] and [third attempt]
                        sed $start,"$end"d yourfile.txt

                        # sed -i $start,"$end"d yourfile.txt # -i - overwite/edit your files in-place instead of printing to standard output





                        share|improve this answer




























                          0














                          I'll try to grep to the two line numbers of "second attempt" and "third attempt" then delete whatever is in between. Edit accordingly to your needs. :)



                          #getting line number for [second attempt]
                          line_num_second=$(grep -n "second attempt" yourfile.txt | cut -d : -f 1)

                          #getting line number for [third attempt]
                          line_num_third=$(grep -n "third attempt" yourfile.txt | cut -d : -f 1)

                          start=$(expr $line_num_second +1)
                          end=$(expr $line_num_third -2)

                          #removes the content in between [second attempt] and [third attempt]
                          sed $start,"$end"d yourfile.txt

                          # sed -i $start,"$end"d yourfile.txt # -i - overwite/edit your files in-place instead of printing to standard output





                          share|improve this answer


























                            0












                            0








                            0







                            I'll try to grep to the two line numbers of "second attempt" and "third attempt" then delete whatever is in between. Edit accordingly to your needs. :)



                            #getting line number for [second attempt]
                            line_num_second=$(grep -n "second attempt" yourfile.txt | cut -d : -f 1)

                            #getting line number for [third attempt]
                            line_num_third=$(grep -n "third attempt" yourfile.txt | cut -d : -f 1)

                            start=$(expr $line_num_second +1)
                            end=$(expr $line_num_third -2)

                            #removes the content in between [second attempt] and [third attempt]
                            sed $start,"$end"d yourfile.txt

                            # sed -i $start,"$end"d yourfile.txt # -i - overwite/edit your files in-place instead of printing to standard output





                            share|improve this answer













                            I'll try to grep to the two line numbers of "second attempt" and "third attempt" then delete whatever is in between. Edit accordingly to your needs. :)



                            #getting line number for [second attempt]
                            line_num_second=$(grep -n "second attempt" yourfile.txt | cut -d : -f 1)

                            #getting line number for [third attempt]
                            line_num_third=$(grep -n "third attempt" yourfile.txt | cut -d : -f 1)

                            start=$(expr $line_num_second +1)
                            end=$(expr $line_num_third -2)

                            #removes the content in between [second attempt] and [third attempt]
                            sed $start,"$end"d yourfile.txt

                            # sed -i $start,"$end"d yourfile.txt # -i - overwite/edit your files in-place instead of printing to standard output






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered 57 mins ago









                            JojoleoJojoleo

                            307




                            307






























                                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%2f237822%2fhow-can-i-remove-lines-under-a-sub-heading-in-a-file-using-linux-commands%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

                                Taj Mahal Inhaltsverzeichnis Aufbau | Geschichte | 350-Jahr-Feier | Heutige Bedeutung | Siehe auch |...

                                Baia Sprie Cuprins Etimologie | Istorie | Demografie | Politică și administrație | Arii naturale...

                                Nicolae Petrescu-Găină Cuprins Biografie | Opera | In memoriam | Varia | Controverse, incertitudini...