Only print output after finding pattern The Next CEO of Stack OverflowHow to sed chunks text from a stream of files from findprint output to 3 separate columnsHow to print to the left and right of already printed outputprint characters repetitively using asterisk symbol in bashformat command output with variable and fixed spaceGet the output in a formatted wayHow to print $STR1 and $STR2 - not their contents - into a file?Print variable with backslashes in dashecho for Print outputBest way to create table-like CLI display in Bash?print a column with the desire format output

Does Germany produce more waste than the US?

How badly should I try to prevent a user from XSSing themselves?

Free fall ellipse or parabola?

Another proof that dividing by 0 does not exist -- is it right?

How can a day be of 24 hours?

Upgrading From a 9 Speed Sora Derailleur?

Is it okay to majorly distort historical facts while writing a fiction story?

Why did early computer designers eschew integers?

Shortening a title without changing its meaning

Why doesn't Shulchan Aruch include the laws of destroying fruit trees?

Is it reasonable to ask other researchers to send me their previous grant applications?

Can this transistor (2N2222) take 6 V on emitter-base? Am I reading the datasheet incorrectly?

Masking layers by a vector polygon layer in QGIS

How should I connect my cat5 cable to connectors having an orange-green line?

How to coordinate airplane tickets?

Is it correct to say moon starry nights?

Early programmable calculators with RS-232

Ising model simulation

Prodigo = pro + ago?

Direct Implications Between USA and UK in Event of No-Deal Brexit

Why can't we say "I have been having a dog"?

What did the word "leisure" mean in late 18th Century usage?

How exploitable/balanced is this homebrew spell: Spell Permanency?

How dangerous is XSS



Only print output after finding pattern



The Next CEO of Stack OverflowHow to sed chunks text from a stream of files from findprint output to 3 separate columnsHow to print to the left and right of already printed outputprint characters repetitively using asterisk symbol in bashformat command output with variable and fixed spaceGet the output in a formatted wayHow to print $STR1 and $STR2 - not their contents - into a file?Print variable with backslashes in dashecho for Print outputBest way to create table-like CLI display in Bash?print a column with the desire format output










13















There's a script (let's call it echoer) that prints to screen a bunch of information. I'd like to be able to only see lines after a pattern is found.



I imagine the usage of a solution to look something like



echoer | solution_command <pattern>


Ideally pattern would be a regular expression, but hard value strings would be enough for me.










share|improve this question









New contributor




user23146 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • So pattern can be multiple strings?

    – Inian
    Mar 28 at 9:41











  • A glob? Do you mean a regular expression? Globs only make sense for file name expansions.

    – terdon
    Mar 28 at 9:47











  • @Inian I'm not sure I understand the question. Do you mean to ask if I want this to work with disjunctions?

    – user23146
    Mar 28 at 10:03















13















There's a script (let's call it echoer) that prints to screen a bunch of information. I'd like to be able to only see lines after a pattern is found.



I imagine the usage of a solution to look something like



echoer | solution_command <pattern>


Ideally pattern would be a regular expression, but hard value strings would be enough for me.










share|improve this question









New contributor




user23146 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • So pattern can be multiple strings?

    – Inian
    Mar 28 at 9:41











  • A glob? Do you mean a regular expression? Globs only make sense for file name expansions.

    – terdon
    Mar 28 at 9:47











  • @Inian I'm not sure I understand the question. Do you mean to ask if I want this to work with disjunctions?

    – user23146
    Mar 28 at 10:03













13












13








13


4






There's a script (let's call it echoer) that prints to screen a bunch of information. I'd like to be able to only see lines after a pattern is found.



I imagine the usage of a solution to look something like



echoer | solution_command <pattern>


Ideally pattern would be a regular expression, but hard value strings would be enough for me.










share|improve this question









New contributor




user23146 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












There's a script (let's call it echoer) that prints to screen a bunch of information. I'd like to be able to only see lines after a pattern is found.



I imagine the usage of a solution to look something like



echoer | solution_command <pattern>


Ideally pattern would be a regular expression, but hard value strings would be enough for me.







echo printf






share|improve this question









New contributor




user23146 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




user23146 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited Mar 28 at 10:02







user23146













New contributor




user23146 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked Mar 28 at 9:39









user23146user23146

684




684




New contributor




user23146 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





user23146 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






user23146 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • So pattern can be multiple strings?

    – Inian
    Mar 28 at 9:41











  • A glob? Do you mean a regular expression? Globs only make sense for file name expansions.

    – terdon
    Mar 28 at 9:47











  • @Inian I'm not sure I understand the question. Do you mean to ask if I want this to work with disjunctions?

    – user23146
    Mar 28 at 10:03

















  • So pattern can be multiple strings?

    – Inian
    Mar 28 at 9:41











  • A glob? Do you mean a regular expression? Globs only make sense for file name expansions.

    – terdon
    Mar 28 at 9:47











  • @Inian I'm not sure I understand the question. Do you mean to ask if I want this to work with disjunctions?

    – user23146
    Mar 28 at 10:03
















So pattern can be multiple strings?

– Inian
Mar 28 at 9:41





So pattern can be multiple strings?

– Inian
Mar 28 at 9:41













A glob? Do you mean a regular expression? Globs only make sense for file name expansions.

– terdon
Mar 28 at 9:47





A glob? Do you mean a regular expression? Globs only make sense for file name expansions.

– terdon
Mar 28 at 9:47













@Inian I'm not sure I understand the question. Do you mean to ask if I want this to work with disjunctions?

– user23146
Mar 28 at 10:03





@Inian I'm not sure I understand the question. Do you mean to ask if I want this to work with disjunctions?

– user23146
Mar 28 at 10:03










6 Answers
6






active

oldest

votes


















20














AWK can do this with pattern ranges, which allows the use of any regular expression:



echoer | awk '/pattern/,0'


will print echoer’s output starting with the first line matching pattern.



AWK is pattern-based, and is typically used with a “if this pattern matches, do this” type of approach. “This pattern” can be a range of patterns, defined as “when this pattern matches, start doing this, until this other pattern matches”; this is specified by writing two patterns separated by a comma, as above. Patterns can be text matches, as in /pattern/, where the current line is checked against the pattern, interpreted as a regular expression; they can also be general expressions, evaluated for every line, and considered to match if their result is non-zero or non-empty.



In AWK, the default action is to print the current line.



Putting all this together, awk '/pattern/,0' looks for lines matching pattern, and once it finds one, applies the default action to all lines until the 0 condition matches (is non-zero). awk '/pattern/,""' would work too.



The Gawk manual goes into much more detail.






share|improve this answer




















  • 3





    I was not aware of the range semantics with zero as the end of the range. Thanks!

    – Kusalananda
    Mar 28 at 10:06











  • @StephenKitt This is great! What if I wanted to print until it matched 0? Would it be /pattern/,/0/? What would the answer look like explicitly writing out the default action?

    – user23146
    Mar 28 at 10:32











  • @user23146 yes, /pattern/,/0/ would print until it found a line (record) containing “0”. Writing the snippet in the answer with an explicit action gives /pattern/,0 print $0 , or equivalently /pattern/,0 print .

    – Stephen Kitt
    Mar 28 at 10:46


















6














The obligatory sed equivalent of @StephenKitt's awk one:



sed '/pattern/,$!d'


pattern there is interpreted as a Basic Regular Expression like in grep (as opposed to Extended Regular Expression in awk/egrep/grep -E). Some sed implementations have a -E (BSD, ast, recent GNU/busybox, soon POSIX) or -r (GNU, ssed, busybox, some recent BSD) option to make it Extended Regular Expressions instead and some have -P (ast) or -R (ssed) to make it a perl-like regular expression.



With perl:



perl -ne 'print if /pattern/ .. undef'





share|improve this answer






























    4














    with GNU and *BSD grep:



    grep -A1000000000 pattern file


    Unless your file has more than 1M lines, that's it.






    share|improve this answer






























      0














      If you're using a pager such as less to view output from the command



      less +pattern





      share|improve this answer






























        0















        awk for lines after (but not including) the first pattern match



        If the line containing the trigger pattern is the equivalent of "CUT HERE", you can omit it from the printed output:



        echoer | awk 'flag ; /pattern/ flag=1 '


        Each line of input runs through two components in the awk code. The first component is flag, which awk interprets as "print the line if the variable flag is nonzero". Since awk variables are 0 by default, this will initially not print anything.



        The second component, /pattern/ flag=1 , sets the flag to 1 as soon as it detects the pattern, and the flag keeps that value for the rest of the run.



        By the time that the pattern is first detected, the opportunity to print that line of input has passed. Any subsequent lines (including additional lines containing the pattern) will print.






        share|improve this answer






























          0














          Bash



          A bit clunky, but it works.



          #!/bin/bash
          found=false
          while IFS= read -r; do
          if $found || [[ $REPLY =~ pattern ]]; then
          found=true
          printf '%sn' "$REPLY"
          fi
          done


          This version relies on cat, but it's easier to understand.



          #!/bin/bash
          while IFS= read -r; do
          if [[ $REPLY =~ pattern ]]; then
          printf '%sn' "$REPLY"
          break
          fi
          done
          cat





          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
            );



            );






            user23146 is a new contributor. Be nice, and check out our Code of Conduct.









            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f509173%2fonly-print-output-after-finding-pattern%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            6 Answers
            6






            active

            oldest

            votes








            6 Answers
            6






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            20














            AWK can do this with pattern ranges, which allows the use of any regular expression:



            echoer | awk '/pattern/,0'


            will print echoer’s output starting with the first line matching pattern.



            AWK is pattern-based, and is typically used with a “if this pattern matches, do this” type of approach. “This pattern” can be a range of patterns, defined as “when this pattern matches, start doing this, until this other pattern matches”; this is specified by writing two patterns separated by a comma, as above. Patterns can be text matches, as in /pattern/, where the current line is checked against the pattern, interpreted as a regular expression; they can also be general expressions, evaluated for every line, and considered to match if their result is non-zero or non-empty.



            In AWK, the default action is to print the current line.



            Putting all this together, awk '/pattern/,0' looks for lines matching pattern, and once it finds one, applies the default action to all lines until the 0 condition matches (is non-zero). awk '/pattern/,""' would work too.



            The Gawk manual goes into much more detail.






            share|improve this answer




















            • 3





              I was not aware of the range semantics with zero as the end of the range. Thanks!

              – Kusalananda
              Mar 28 at 10:06











            • @StephenKitt This is great! What if I wanted to print until it matched 0? Would it be /pattern/,/0/? What would the answer look like explicitly writing out the default action?

              – user23146
              Mar 28 at 10:32











            • @user23146 yes, /pattern/,/0/ would print until it found a line (record) containing “0”. Writing the snippet in the answer with an explicit action gives /pattern/,0 print $0 , or equivalently /pattern/,0 print .

              – Stephen Kitt
              Mar 28 at 10:46















            20














            AWK can do this with pattern ranges, which allows the use of any regular expression:



            echoer | awk '/pattern/,0'


            will print echoer’s output starting with the first line matching pattern.



            AWK is pattern-based, and is typically used with a “if this pattern matches, do this” type of approach. “This pattern” can be a range of patterns, defined as “when this pattern matches, start doing this, until this other pattern matches”; this is specified by writing two patterns separated by a comma, as above. Patterns can be text matches, as in /pattern/, where the current line is checked against the pattern, interpreted as a regular expression; they can also be general expressions, evaluated for every line, and considered to match if their result is non-zero or non-empty.



            In AWK, the default action is to print the current line.



            Putting all this together, awk '/pattern/,0' looks for lines matching pattern, and once it finds one, applies the default action to all lines until the 0 condition matches (is non-zero). awk '/pattern/,""' would work too.



            The Gawk manual goes into much more detail.






            share|improve this answer




















            • 3





              I was not aware of the range semantics with zero as the end of the range. Thanks!

              – Kusalananda
              Mar 28 at 10:06











            • @StephenKitt This is great! What if I wanted to print until it matched 0? Would it be /pattern/,/0/? What would the answer look like explicitly writing out the default action?

              – user23146
              Mar 28 at 10:32











            • @user23146 yes, /pattern/,/0/ would print until it found a line (record) containing “0”. Writing the snippet in the answer with an explicit action gives /pattern/,0 print $0 , or equivalently /pattern/,0 print .

              – Stephen Kitt
              Mar 28 at 10:46













            20












            20








            20







            AWK can do this with pattern ranges, which allows the use of any regular expression:



            echoer | awk '/pattern/,0'


            will print echoer’s output starting with the first line matching pattern.



            AWK is pattern-based, and is typically used with a “if this pattern matches, do this” type of approach. “This pattern” can be a range of patterns, defined as “when this pattern matches, start doing this, until this other pattern matches”; this is specified by writing two patterns separated by a comma, as above. Patterns can be text matches, as in /pattern/, where the current line is checked against the pattern, interpreted as a regular expression; they can also be general expressions, evaluated for every line, and considered to match if their result is non-zero or non-empty.



            In AWK, the default action is to print the current line.



            Putting all this together, awk '/pattern/,0' looks for lines matching pattern, and once it finds one, applies the default action to all lines until the 0 condition matches (is non-zero). awk '/pattern/,""' would work too.



            The Gawk manual goes into much more detail.






            share|improve this answer















            AWK can do this with pattern ranges, which allows the use of any regular expression:



            echoer | awk '/pattern/,0'


            will print echoer’s output starting with the first line matching pattern.



            AWK is pattern-based, and is typically used with a “if this pattern matches, do this” type of approach. “This pattern” can be a range of patterns, defined as “when this pattern matches, start doing this, until this other pattern matches”; this is specified by writing two patterns separated by a comma, as above. Patterns can be text matches, as in /pattern/, where the current line is checked against the pattern, interpreted as a regular expression; they can also be general expressions, evaluated for every line, and considered to match if their result is non-zero or non-empty.



            In AWK, the default action is to print the current line.



            Putting all this together, awk '/pattern/,0' looks for lines matching pattern, and once it finds one, applies the default action to all lines until the 0 condition matches (is non-zero). awk '/pattern/,""' would work too.



            The Gawk manual goes into much more detail.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 28 at 14:24

























            answered Mar 28 at 9:46









            Stephen KittStephen Kitt

            179k24407485




            179k24407485







            • 3





              I was not aware of the range semantics with zero as the end of the range. Thanks!

              – Kusalananda
              Mar 28 at 10:06











            • @StephenKitt This is great! What if I wanted to print until it matched 0? Would it be /pattern/,/0/? What would the answer look like explicitly writing out the default action?

              – user23146
              Mar 28 at 10:32











            • @user23146 yes, /pattern/,/0/ would print until it found a line (record) containing “0”. Writing the snippet in the answer with an explicit action gives /pattern/,0 print $0 , or equivalently /pattern/,0 print .

              – Stephen Kitt
              Mar 28 at 10:46












            • 3





              I was not aware of the range semantics with zero as the end of the range. Thanks!

              – Kusalananda
              Mar 28 at 10:06











            • @StephenKitt This is great! What if I wanted to print until it matched 0? Would it be /pattern/,/0/? What would the answer look like explicitly writing out the default action?

              – user23146
              Mar 28 at 10:32











            • @user23146 yes, /pattern/,/0/ would print until it found a line (record) containing “0”. Writing the snippet in the answer with an explicit action gives /pattern/,0 print $0 , or equivalently /pattern/,0 print .

              – Stephen Kitt
              Mar 28 at 10:46







            3




            3





            I was not aware of the range semantics with zero as the end of the range. Thanks!

            – Kusalananda
            Mar 28 at 10:06





            I was not aware of the range semantics with zero as the end of the range. Thanks!

            – Kusalananda
            Mar 28 at 10:06













            @StephenKitt This is great! What if I wanted to print until it matched 0? Would it be /pattern/,/0/? What would the answer look like explicitly writing out the default action?

            – user23146
            Mar 28 at 10:32





            @StephenKitt This is great! What if I wanted to print until it matched 0? Would it be /pattern/,/0/? What would the answer look like explicitly writing out the default action?

            – user23146
            Mar 28 at 10:32













            @user23146 yes, /pattern/,/0/ would print until it found a line (record) containing “0”. Writing the snippet in the answer with an explicit action gives /pattern/,0 print $0 , or equivalently /pattern/,0 print .

            – Stephen Kitt
            Mar 28 at 10:46





            @user23146 yes, /pattern/,/0/ would print until it found a line (record) containing “0”. Writing the snippet in the answer with an explicit action gives /pattern/,0 print $0 , or equivalently /pattern/,0 print .

            – Stephen Kitt
            Mar 28 at 10:46













            6














            The obligatory sed equivalent of @StephenKitt's awk one:



            sed '/pattern/,$!d'


            pattern there is interpreted as a Basic Regular Expression like in grep (as opposed to Extended Regular Expression in awk/egrep/grep -E). Some sed implementations have a -E (BSD, ast, recent GNU/busybox, soon POSIX) or -r (GNU, ssed, busybox, some recent BSD) option to make it Extended Regular Expressions instead and some have -P (ast) or -R (ssed) to make it a perl-like regular expression.



            With perl:



            perl -ne 'print if /pattern/ .. undef'





            share|improve this answer



























              6














              The obligatory sed equivalent of @StephenKitt's awk one:



              sed '/pattern/,$!d'


              pattern there is interpreted as a Basic Regular Expression like in grep (as opposed to Extended Regular Expression in awk/egrep/grep -E). Some sed implementations have a -E (BSD, ast, recent GNU/busybox, soon POSIX) or -r (GNU, ssed, busybox, some recent BSD) option to make it Extended Regular Expressions instead and some have -P (ast) or -R (ssed) to make it a perl-like regular expression.



              With perl:



              perl -ne 'print if /pattern/ .. undef'





              share|improve this answer

























                6












                6








                6







                The obligatory sed equivalent of @StephenKitt's awk one:



                sed '/pattern/,$!d'


                pattern there is interpreted as a Basic Regular Expression like in grep (as opposed to Extended Regular Expression in awk/egrep/grep -E). Some sed implementations have a -E (BSD, ast, recent GNU/busybox, soon POSIX) or -r (GNU, ssed, busybox, some recent BSD) option to make it Extended Regular Expressions instead and some have -P (ast) or -R (ssed) to make it a perl-like regular expression.



                With perl:



                perl -ne 'print if /pattern/ .. undef'





                share|improve this answer













                The obligatory sed equivalent of @StephenKitt's awk one:



                sed '/pattern/,$!d'


                pattern there is interpreted as a Basic Regular Expression like in grep (as opposed to Extended Regular Expression in awk/egrep/grep -E). Some sed implementations have a -E (BSD, ast, recent GNU/busybox, soon POSIX) or -r (GNU, ssed, busybox, some recent BSD) option to make it Extended Regular Expressions instead and some have -P (ast) or -R (ssed) to make it a perl-like regular expression.



                With perl:



                perl -ne 'print if /pattern/ .. undef'






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 28 at 14:48









                Stéphane ChazelasStéphane Chazelas

                312k57591948




                312k57591948





















                    4














                    with GNU and *BSD grep:



                    grep -A1000000000 pattern file


                    Unless your file has more than 1M lines, that's it.






                    share|improve this answer



























                      4














                      with GNU and *BSD grep:



                      grep -A1000000000 pattern file


                      Unless your file has more than 1M lines, that's it.






                      share|improve this answer

























                        4












                        4








                        4







                        with GNU and *BSD grep:



                        grep -A1000000000 pattern file


                        Unless your file has more than 1M lines, that's it.






                        share|improve this answer













                        with GNU and *BSD grep:



                        grep -A1000000000 pattern file


                        Unless your file has more than 1M lines, that's it.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Mar 28 at 14:55









                        mosvymosvy

                        8,8621833




                        8,8621833





















                            0














                            If you're using a pager such as less to view output from the command



                            less +pattern





                            share|improve this answer



























                              0














                              If you're using a pager such as less to view output from the command



                              less +pattern





                              share|improve this answer

























                                0












                                0








                                0







                                If you're using a pager such as less to view output from the command



                                less +pattern





                                share|improve this answer













                                If you're using a pager such as less to view output from the command



                                less +pattern






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Mar 29 at 2:29









                                iruvariruvar

                                12.2k63062




                                12.2k63062





















                                    0















                                    awk for lines after (but not including) the first pattern match



                                    If the line containing the trigger pattern is the equivalent of "CUT HERE", you can omit it from the printed output:



                                    echoer | awk 'flag ; /pattern/ flag=1 '


                                    Each line of input runs through two components in the awk code. The first component is flag, which awk interprets as "print the line if the variable flag is nonzero". Since awk variables are 0 by default, this will initially not print anything.



                                    The second component, /pattern/ flag=1 , sets the flag to 1 as soon as it detects the pattern, and the flag keeps that value for the rest of the run.



                                    By the time that the pattern is first detected, the opportunity to print that line of input has passed. Any subsequent lines (including additional lines containing the pattern) will print.






                                    share|improve this answer



























                                      0















                                      awk for lines after (but not including) the first pattern match



                                      If the line containing the trigger pattern is the equivalent of "CUT HERE", you can omit it from the printed output:



                                      echoer | awk 'flag ; /pattern/ flag=1 '


                                      Each line of input runs through two components in the awk code. The first component is flag, which awk interprets as "print the line if the variable flag is nonzero". Since awk variables are 0 by default, this will initially not print anything.



                                      The second component, /pattern/ flag=1 , sets the flag to 1 as soon as it detects the pattern, and the flag keeps that value for the rest of the run.



                                      By the time that the pattern is first detected, the opportunity to print that line of input has passed. Any subsequent lines (including additional lines containing the pattern) will print.






                                      share|improve this answer

























                                        0












                                        0








                                        0








                                        awk for lines after (but not including) the first pattern match



                                        If the line containing the trigger pattern is the equivalent of "CUT HERE", you can omit it from the printed output:



                                        echoer | awk 'flag ; /pattern/ flag=1 '


                                        Each line of input runs through two components in the awk code. The first component is flag, which awk interprets as "print the line if the variable flag is nonzero". Since awk variables are 0 by default, this will initially not print anything.



                                        The second component, /pattern/ flag=1 , sets the flag to 1 as soon as it detects the pattern, and the flag keeps that value for the rest of the run.



                                        By the time that the pattern is first detected, the opportunity to print that line of input has passed. Any subsequent lines (including additional lines containing the pattern) will print.






                                        share|improve this answer














                                        awk for lines after (but not including) the first pattern match



                                        If the line containing the trigger pattern is the equivalent of "CUT HERE", you can omit it from the printed output:



                                        echoer | awk 'flag ; /pattern/ flag=1 '


                                        Each line of input runs through two components in the awk code. The first component is flag, which awk interprets as "print the line if the variable flag is nonzero". Since awk variables are 0 by default, this will initially not print anything.



                                        The second component, /pattern/ flag=1 , sets the flag to 1 as soon as it detects the pattern, and the flag keeps that value for the rest of the run.



                                        By the time that the pattern is first detected, the opportunity to print that line of input has passed. Any subsequent lines (including additional lines containing the pattern) will print.







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Mar 29 at 2:53









                                        GaultheriaGaultheria

                                        34214




                                        34214





















                                            0














                                            Bash



                                            A bit clunky, but it works.



                                            #!/bin/bash
                                            found=false
                                            while IFS= read -r; do
                                            if $found || [[ $REPLY =~ pattern ]]; then
                                            found=true
                                            printf '%sn' "$REPLY"
                                            fi
                                            done


                                            This version relies on cat, but it's easier to understand.



                                            #!/bin/bash
                                            while IFS= read -r; do
                                            if [[ $REPLY =~ pattern ]]; then
                                            printf '%sn' "$REPLY"
                                            break
                                            fi
                                            done
                                            cat





                                            share|improve this answer





























                                              0














                                              Bash



                                              A bit clunky, but it works.



                                              #!/bin/bash
                                              found=false
                                              while IFS= read -r; do
                                              if $found || [[ $REPLY =~ pattern ]]; then
                                              found=true
                                              printf '%sn' "$REPLY"
                                              fi
                                              done


                                              This version relies on cat, but it's easier to understand.



                                              #!/bin/bash
                                              while IFS= read -r; do
                                              if [[ $REPLY =~ pattern ]]; then
                                              printf '%sn' "$REPLY"
                                              break
                                              fi
                                              done
                                              cat





                                              share|improve this answer



























                                                0












                                                0








                                                0







                                                Bash



                                                A bit clunky, but it works.



                                                #!/bin/bash
                                                found=false
                                                while IFS= read -r; do
                                                if $found || [[ $REPLY =~ pattern ]]; then
                                                found=true
                                                printf '%sn' "$REPLY"
                                                fi
                                                done


                                                This version relies on cat, but it's easier to understand.



                                                #!/bin/bash
                                                while IFS= read -r; do
                                                if [[ $REPLY =~ pattern ]]; then
                                                printf '%sn' "$REPLY"
                                                break
                                                fi
                                                done
                                                cat





                                                share|improve this answer















                                                Bash



                                                A bit clunky, but it works.



                                                #!/bin/bash
                                                found=false
                                                while IFS= read -r; do
                                                if $found || [[ $REPLY =~ pattern ]]; then
                                                found=true
                                                printf '%sn' "$REPLY"
                                                fi
                                                done


                                                This version relies on cat, but it's easier to understand.



                                                #!/bin/bash
                                                while IFS= read -r; do
                                                if [[ $REPLY =~ pattern ]]; then
                                                printf '%sn' "$REPLY"
                                                break
                                                fi
                                                done
                                                cat






                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Mar 29 at 2:53

























                                                answered Mar 29 at 2:18









                                                wjandreawjandrea

                                                504413




                                                504413




















                                                    user23146 is a new contributor. Be nice, and check out our Code of Conduct.









                                                    draft saved

                                                    draft discarded


















                                                    user23146 is a new contributor. Be nice, and check out our Code of Conduct.












                                                    user23146 is a new contributor. Be nice, and check out our Code of Conduct.











                                                    user23146 is a new contributor. Be nice, and check out our Code of Conduct.














                                                    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%2f509173%2fonly-print-output-after-finding-pattern%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

                                                    Triangular numbers and gcdProving sum of a set is $0 pmod n$ if $n$ is odd, or $fracn2 pmod n$ if $n$ is even?Is greatest common divisor of two numbers really their smallest linear combination?GCD, LCM RelationshipProve a set of nonnegative integers with greatest common divisor 1 and closed under addition has all but finite many nonnegative integers.all pairs of a and b in an equation containing gcdTriangular Numbers Modulo $k$ - Hit All Values?Understanding the Existence and Uniqueness of the GCDGCD and LCM with logical symbolsThe greatest common divisor of two positive integers less than 100 is equal to 3. Their least common multiple is twelve times one of the integers.Suppose that for all integers $x$, $x|a$ and $x|b$ if and only if $x|c$. Then $c = gcd(a,b)$Which is the gcd of 2 numbers which are multiplied and the result is 600000?

                                                    Србија Садржај Етимологија Географија Историја Политички систем и уставно-правно уређење Становништво Привреда Образовање Култура Спорт Државни празници Галерија Напомене Референце Литература Спољашње везе Мени за навигацију44°48′N 20°28′E / 44.800° СГШ; 20.467° ИГД / 44.800; 20.46744°48′N 20°28′E / 44.800° СГШ; 20.467° ИГД / 44.800; 20.467ууРезултати пописа 2011. према старости и полуу„Положај, рељеф и клима”„Europe: Serbia”„Основни подаци”„Gross domestic product based on purchasing-power-parity (PPP) valuation of country GDP”„Human Development Report 2018 – "Human Development Indices and Indicators 6”„Устав Републике Србије”Правопис српскога језикаGoogle DriveComparative Hungarian Cultural StudiesCalcium and Magnesium in Groundwater: Occurrence and Significance for Human Health„UNSD — Methodology”„Процене становништва | Републички завод за статистику Србије”The Age of Nepotism: Travel Journals and Observations from the Balkans During the Depression„The Serbian Revolution and the Serbian State”„Устав Србије”„Serbia a few steps away from concluding WTO accession negotiations”„A credible enlargement perspective for and enhanced EU engagement with the Western Balkans”„Freedom in the World 2017”„Serbia: On the Way to EU Accession”„Human Development Indices and Indicators: 2018 Statistical Update”„2018 Social Progress Index”„Global Peace Index”Sabres of Two Easts: An Untold History of Muslims in Eastern Europe, Their Friends and Foes„Пројекат Растко—Лузица”„Serbia: Introduction”„Serbia”оригинала„The World Factbook: Serbia”„The World Factbook: Kosovo”„Border Police Department”„Uredba o kontroli prelaska administrativne linije prema Autonomnoj pokrajini Kosovo i Metohija”оригиналаIvana Carevic, Velimir Jovanovic, STRATIGRAPHIC-STRUCTURAL CHARACTERISTICS OF MAČVA BASIN, UDC 911.2:551.7(497.11), pp. 1Archived„About the Carpathians – Carpathian Heritage Society”оригинала„O Srbiji”оригинала„Статистички годишњак Србије, 2009: Географски прегледГеографија за осми разред основне школе„Отворена, електронска база едукационих радова”„Влада Републике Србије: Положај, рељеф и клима”„Копрен (Стара планина)”„Туристичка дестинација-Србија”„Висина водопада”„РХМЗ — Републички Хидрометеоролошки завод Србије Кнеза Вишеслава 66 Београд”„Фауна Србије”„Српске шуме на издисају”„Lepih šest odsto Srbije”„Илустрована историја Срба — Увод”„Винчанска култура - Градска општина Гроцка”„''„Винча — Праисторијска метропола”''”оригиналаЈужни Словени под византијском влашћу (600—1025)Држава маћедонских Словена„Карађорђе истина и мит, Проф. др Радош Љушић, Вечерње новости, фељтон, 18 наставака, 24. август - 10. септембар 2003.”„Политика: Како је утврђена војна неутралност, 13. јануар. 2010, приступљено децембра 2012.”„Србија и РС оживеле Дејтонски споразум”„Са српским пасошем у 104 земље”Војска Србије | О Војсци | Војска Србије — Улога, намена и задациАрхивираноВојска Србије | ОрганизацијаАрхивираноОдлука о изради Стратегије просторног развоја Републике Србије до 2020. годинеЗакон о територијалној организацији Републике СрбијеЗакон о државној управиНајчешће постављана питања.„Смањење броја статистичких региона кроз измене Закона о регионалном развоју”„2011 Human development Report”„Službena upotreba jezika i pisama”„Попис становништва, домаћинстава и станова 2011. године у Републици Србији. Књига 4: Вероисповест, матерњи језик и национална припадност”„Вероисповест, матерњи језик и национална”„Специјална известитељка УН за слободу религије и вероисповести Асма Јахангир, код Заштитника грађана Саше Јанковића”„Закон о државним и другим празницима у Републици Србији”„Веронаука у српским школама”„Serbia – Ancestral Genography Atlas”Бела књига Милошевићеве владавинеоригиналаGross domestic product based on purchasing-power-parity (PPP) per capita GDP БДП 2007—2013Актуелни показатељи — Република Србија„Попис становништва, домаћинстава и станова 2011. године у Републици Србији Књига 7: Економска активност”Zemlje kandidati za članstvo u EU„Putin drops South Stream gas pipeline to EU, courts Turkey”„„Соко — историјат””оригинала„„Рембас — историјат””оригинала„„Лубница — историјат””оригинала„„Штаваљ — Историјат””оригинала„„Боговина — историјат””оригинала„„Јасеновац — историјат””оригинала„„Вршка чука — историјат””оригинала„„Ибарски рудници — историјат””оригинала„Закон о просторном плану Републике Србије од 2010 до 2020”„Кривични законик — Недозвољена изградња нуклеарних постројења, члан 267”„Б92: Srbija uklonila obogaćeni uranijum, 25. октобар 2011”„Коришћење енергије ветра у Србији — природни услови и практична примена”„Енергија ветра”„Србија може да прави струју од сунца, биомасе, воде и ветра”„Моја електрана и друге ветрењаче”„Биомаса, струја без инвестиција”„Auto-karte Srbije”„www.srbija.gov.rs Статистике о Србији”оригинала„Статистика зе месец децембар и 2016. годину”„Turizam u Srbiji”„Univerzitet u Beogradu: Vek i po akademskog znanja”„Vojnomedicinska akademija: 165 godina tradicije i napretka”Никола Гиљен, Соња Јовићевић Јов и Јелена Мандић: Мирослављево јеванђеље; Текст је публикован у ревији „Историја” и настао је као део научно-истраживачког рада Фонда „Принцеза Оливера”„World music асоцијација Србије”оригинала„World music у Србији”оригинала„Pogledajte: Boban Marković svira u redakciji „Blica”!”„Eurovision Song Contest 2007 Final”„Projekat Rastko, Alojz Ujes: Joakim Vujic”„Унеско”„Списак локалитета Светске баштине”„Guča i Egzit zaludeli svet”оригинала„Sabor trubača GUČA”„Interesting facts about Exit”оригинала„FIFA Association Information”„Serbia women win EuroBasket title, gain first Olympics berth”„Odbojkašice ispisale istoriju – Srbija je svetski prvak!”„Сајт Ватерполо савеза Србије, Освојене медаље”„Сајт ФК Црвена звезда, Бари”„Сајт ФК Црвена звезда, Токио”„Blic:Zlatna Milica! Mandićeva donela Srbiji najsjajnije odličje u Londonu!”„Милица Мандић освојила златну медаљу („Политика”, 12. август 2012)”„Златни Давор Штефанек”„DŽUDO ŠAMPIONAT Majdov osvojio svetsko zlato”„Španovićeva trećim skokom svih vremena do zlata!”„Чудо Иване Шпановић — 7,24 м („Политика”, 5. март 2017)”The Age of Nepotism: Travel Journals and Observations from the Balkans During the DepressionCalcium and Magnesium in Groundwater: Occurrence and Significance for Human HealthComparative Hungarian Cultural StudiesБела књига Милошевићеве владавинеоригиналаComparative Hungarian Cultural StudiesSabres of Two Easts: An Untold History of Muslims in Eastern Europe, Their Friends and FoesГеографија за осми разред основне школеSerbia: the country, people, life, customsМедијиВодичПодациВлада Републике СрбијеНародна скупштина Републике СрбијеНародна канцеларија председника Републике СрбијеНародна банка СрбијеТуристичка организација СрбијеПортал еУправе Републике СрбијеРепубличко јавно правобранилаштвоууууууWorldCat151202876n851959190000 0000 9526 67094054598-24101000570825ge130919

                                                    Barbados Ynhâld Skiednis | Geografy | Demografy | Navigaasjemenu