Count number of occurrences of a pattern on same line2019 Community Moderator ElectionWhy is printf better than echo?Count lines matching pattern and matching previous lineCount number of sessions and email as a bodyFind strings in file1, count occurrences in file2To count number of matches in a mega string quicklyCount number of occurrences of a parentheses regexCount pattern and matching lines simultaneouslyHow to use sed to replace a string using the line number on a remote machine using ssh?How to count occurrences of each word belonging to a file in all of `n` number of files passed as arguments?Returning only the contents before and after a line number with different matching wordsCount the number of occurrences of a substring in a string

Did I make a mistake by ccing email to boss to others?

Given this phrasing in the lease, when should I pay my rent?

If Captain Marvel (MCU) were to have a child with a human male, would the child be human or Kree?

Isometric embedding of a genus g surface

Why didn’t Eve recognize the little cockroach as a living organism?

Why is the Sun approximated as a black body at ~ 5800 K?

Deciphering cause of death?

What is the meaning of the following sentence?

Why is the principal energy of an electron lower for excited electrons in a higher energy state?

How were servants to the Kaiser of Imperial Germany treated and where may I find more information on them

Should I warn new/prospective PhD Student that supervisor is terrible?

Do I have to know the General Relativity theory to understand the concept of inertial frame?

I'm just a whisper. Who am I?

Echo with obfuscation

Why do Radio Buttons not fill the entire outer circle?

How to get directions in deep space?

How to reduce predictors the right way for a logistic regression model

How do I Interface a PS/2 Keyboard without Modern Techniques?

Sound waves in different octaves

How to leave product feedback on macOS?

Giving feedback to someone without sounding prejudiced

Is it feasible to let a newcomer play the "Gandalf"-like figure I created for my campaign?

Is there anyway, I can have two passwords for my wi-fi

Integral Notations in Quantum Mechanics



Count number of occurrences of a pattern on same line



2019 Community Moderator ElectionWhy is printf better than echo?Count lines matching pattern and matching previous lineCount number of sessions and email as a bodyFind strings in file1, count occurrences in file2To count number of matches in a mega string quicklyCount number of occurrences of a parentheses regexCount pattern and matching lines simultaneouslyHow to use sed to replace a string using the line number on a remote machine using ssh?How to count occurrences of each word belonging to a file in all of `n` number of files passed as arguments?Returning only the contents before and after a line number with different matching wordsCount the number of occurrences of a substring in a string










0















I need to solve this in a shell script. I am counting number of occurrence of the abc string below and I want to get the answer as 3.




echo abcsdabcsdabc | grep -o abc

abc

abc

abc




Assuming we do not have the -o option in grep, how do we approach this then?










share|improve this question
























  • What shell are you using? bash?

    – Kusalananda
    20 hours ago











  • If your input string is known to contain no newlines, you can just feed the output to wc echo abcsdabcsdabc | grep -o abc| wc -l, to count the lines.

    – zeppelin
    20 hours ago















0















I need to solve this in a shell script. I am counting number of occurrence of the abc string below and I want to get the answer as 3.




echo abcsdabcsdabc | grep -o abc

abc

abc

abc




Assuming we do not have the -o option in grep, how do we approach this then?










share|improve this question
























  • What shell are you using? bash?

    – Kusalananda
    20 hours ago











  • If your input string is known to contain no newlines, you can just feed the output to wc echo abcsdabcsdabc | grep -o abc| wc -l, to count the lines.

    – zeppelin
    20 hours ago













0












0








0








I need to solve this in a shell script. I am counting number of occurrence of the abc string below and I want to get the answer as 3.




echo abcsdabcsdabc | grep -o abc

abc

abc

abc




Assuming we do not have the -o option in grep, how do we approach this then?










share|improve this question
















I need to solve this in a shell script. I am counting number of occurrence of the abc string below and I want to get the answer as 3.




echo abcsdabcsdabc | grep -o abc

abc

abc

abc




Assuming we do not have the -o option in grep, how do we approach this then?







shell-script






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 20 hours ago









Rui F Ribeiro

41.6k1483141




41.6k1483141










asked 20 hours ago









MachineMachine

244




244












  • What shell are you using? bash?

    – Kusalananda
    20 hours ago











  • If your input string is known to contain no newlines, you can just feed the output to wc echo abcsdabcsdabc | grep -o abc| wc -l, to count the lines.

    – zeppelin
    20 hours ago

















  • What shell are you using? bash?

    – Kusalananda
    20 hours ago











  • If your input string is known to contain no newlines, you can just feed the output to wc echo abcsdabcsdabc | grep -o abc| wc -l, to count the lines.

    – zeppelin
    20 hours ago
















What shell are you using? bash?

– Kusalananda
20 hours ago





What shell are you using? bash?

– Kusalananda
20 hours ago













If your input string is known to contain no newlines, you can just feed the output to wc echo abcsdabcsdabc | grep -o abc| wc -l, to count the lines.

– zeppelin
20 hours ago





If your input string is known to contain no newlines, you can just feed the output to wc echo abcsdabcsdabc | grep -o abc| wc -l, to count the lines.

– zeppelin
20 hours ago










2 Answers
2






active

oldest

votes


















3














With awk:



awk 'BEGINprint gsub(ARGV[2], "&", ARGV[1])' abcsdabcsdabc abc


Note that the pattern (here abc) is taken by awk as an extended regular expression (as if using grep -E/egrep).



That syntax allows both the subject and regexp to contain multiple lines. We also avoid the usual problems associated with echo which can't output arbitrary data.



To use perl regular expressions (similar to GNU grep -P's):



perl -le 'print scalar (() = $ARGV[0] =~ m$ARGV[1]g)' -- abcsdabcsdabc abc


(note however that the arguments are not interpreted as text as per the locale's encoding. For instance in a UTF-8 locale, with é and . as arguments, it would report 2 (bytes) instead of 1 (character)).






share|improve this answer
































    2














    Treating the string as consisting of fields that are delimited by abc:



    $ echo abcsdabcsdabc | awk -F 'abc' ' print NF - 1 '
    3


    The number of occurrences of the delimiter abc is 1 minus the number of fields that it delimits.



    $ echo abcsdabcsdabc | awk ' n=0; while (sub("abc", "")) n++; print n '
    3


    This deletes the substring abc from the line and counts the number of times this is done, then outputs that number. The n=0 is not needed if there is only one line of input.



    The gsub() function in awk returns the number of substitutions made, so the above could be simplified into



    $ echo abcsdabcsdabc | awk ' print gsub("abc", "") '
    3


    In bash, you can do the same thing as in that awk program that uses sub():



    string=abcsdabcsdabc

    n=0
    while [[ $string == *abc* ]]; do
    n=$(( n+1 ))
    string=$string/abc/ # remove first occurrence of "abc"
    done
    printf '%dn' "$n"


    This uses a while loop to remove the substring abc from the value in $string until no further occurrences of abc is found in $string, just as the second awk program above does.






    share|improve this answer

























    • Hi , Can u explain me on bash piece of code. not able to get how n will get value assigned to itself when we are just dealing with single line of input. Please help to explain line wise

      – Machine
      19 hours ago







    • 1





      @Machine I've explained it further now. The loop is looping until no abc is found in $string.

      – Kusalananda
      19 hours ago











    • string=$string/abc/ -- I never used this , so i believe this is inbuilt feature in unix.If u can elaborate more here

      – Machine
      19 hours ago






    • 1





      @Machine This is a bash-specific variable substitution that replaces the first occurrence abc in $string with nothing. The general form is $variable/pattern/word which replaces the first bit that matches pattern in $variable with word. Using $variable//pattern/word replaces all matches. This is described in the bash manual. It is a feature of the shell, not of Unix.

      – Kusalananda
      18 hours ago











    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%2f507368%2fcount-number-of-occurrences-of-a-pattern-on-same-line%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    With awk:



    awk 'BEGINprint gsub(ARGV[2], "&", ARGV[1])' abcsdabcsdabc abc


    Note that the pattern (here abc) is taken by awk as an extended regular expression (as if using grep -E/egrep).



    That syntax allows both the subject and regexp to contain multiple lines. We also avoid the usual problems associated with echo which can't output arbitrary data.



    To use perl regular expressions (similar to GNU grep -P's):



    perl -le 'print scalar (() = $ARGV[0] =~ m$ARGV[1]g)' -- abcsdabcsdabc abc


    (note however that the arguments are not interpreted as text as per the locale's encoding. For instance in a UTF-8 locale, with é and . as arguments, it would report 2 (bytes) instead of 1 (character)).






    share|improve this answer





























      3














      With awk:



      awk 'BEGINprint gsub(ARGV[2], "&", ARGV[1])' abcsdabcsdabc abc


      Note that the pattern (here abc) is taken by awk as an extended regular expression (as if using grep -E/egrep).



      That syntax allows both the subject and regexp to contain multiple lines. We also avoid the usual problems associated with echo which can't output arbitrary data.



      To use perl regular expressions (similar to GNU grep -P's):



      perl -le 'print scalar (() = $ARGV[0] =~ m$ARGV[1]g)' -- abcsdabcsdabc abc


      (note however that the arguments are not interpreted as text as per the locale's encoding. For instance in a UTF-8 locale, with é and . as arguments, it would report 2 (bytes) instead of 1 (character)).






      share|improve this answer



























        3












        3








        3







        With awk:



        awk 'BEGINprint gsub(ARGV[2], "&", ARGV[1])' abcsdabcsdabc abc


        Note that the pattern (here abc) is taken by awk as an extended regular expression (as if using grep -E/egrep).



        That syntax allows both the subject and regexp to contain multiple lines. We also avoid the usual problems associated with echo which can't output arbitrary data.



        To use perl regular expressions (similar to GNU grep -P's):



        perl -le 'print scalar (() = $ARGV[0] =~ m$ARGV[1]g)' -- abcsdabcsdabc abc


        (note however that the arguments are not interpreted as text as per the locale's encoding. For instance in a UTF-8 locale, with é and . as arguments, it would report 2 (bytes) instead of 1 (character)).






        share|improve this answer















        With awk:



        awk 'BEGINprint gsub(ARGV[2], "&", ARGV[1])' abcsdabcsdabc abc


        Note that the pattern (here abc) is taken by awk as an extended regular expression (as if using grep -E/egrep).



        That syntax allows both the subject and regexp to contain multiple lines. We also avoid the usual problems associated with echo which can't output arbitrary data.



        To use perl regular expressions (similar to GNU grep -P's):



        perl -le 'print scalar (() = $ARGV[0] =~ m$ARGV[1]g)' -- abcsdabcsdabc abc


        (note however that the arguments are not interpreted as text as per the locale's encoding. For instance in a UTF-8 locale, with é and . as arguments, it would report 2 (bytes) instead of 1 (character)).







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 19 hours ago

























        answered 20 hours ago









        Stéphane ChazelasStéphane Chazelas

        310k57586945




        310k57586945























            2














            Treating the string as consisting of fields that are delimited by abc:



            $ echo abcsdabcsdabc | awk -F 'abc' ' print NF - 1 '
            3


            The number of occurrences of the delimiter abc is 1 minus the number of fields that it delimits.



            $ echo abcsdabcsdabc | awk ' n=0; while (sub("abc", "")) n++; print n '
            3


            This deletes the substring abc from the line and counts the number of times this is done, then outputs that number. The n=0 is not needed if there is only one line of input.



            The gsub() function in awk returns the number of substitutions made, so the above could be simplified into



            $ echo abcsdabcsdabc | awk ' print gsub("abc", "") '
            3


            In bash, you can do the same thing as in that awk program that uses sub():



            string=abcsdabcsdabc

            n=0
            while [[ $string == *abc* ]]; do
            n=$(( n+1 ))
            string=$string/abc/ # remove first occurrence of "abc"
            done
            printf '%dn' "$n"


            This uses a while loop to remove the substring abc from the value in $string until no further occurrences of abc is found in $string, just as the second awk program above does.






            share|improve this answer

























            • Hi , Can u explain me on bash piece of code. not able to get how n will get value assigned to itself when we are just dealing with single line of input. Please help to explain line wise

              – Machine
              19 hours ago







            • 1





              @Machine I've explained it further now. The loop is looping until no abc is found in $string.

              – Kusalananda
              19 hours ago











            • string=$string/abc/ -- I never used this , so i believe this is inbuilt feature in unix.If u can elaborate more here

              – Machine
              19 hours ago






            • 1





              @Machine This is a bash-specific variable substitution that replaces the first occurrence abc in $string with nothing. The general form is $variable/pattern/word which replaces the first bit that matches pattern in $variable with word. Using $variable//pattern/word replaces all matches. This is described in the bash manual. It is a feature of the shell, not of Unix.

              – Kusalananda
              18 hours ago
















            2














            Treating the string as consisting of fields that are delimited by abc:



            $ echo abcsdabcsdabc | awk -F 'abc' ' print NF - 1 '
            3


            The number of occurrences of the delimiter abc is 1 minus the number of fields that it delimits.



            $ echo abcsdabcsdabc | awk ' n=0; while (sub("abc", "")) n++; print n '
            3


            This deletes the substring abc from the line and counts the number of times this is done, then outputs that number. The n=0 is not needed if there is only one line of input.



            The gsub() function in awk returns the number of substitutions made, so the above could be simplified into



            $ echo abcsdabcsdabc | awk ' print gsub("abc", "") '
            3


            In bash, you can do the same thing as in that awk program that uses sub():



            string=abcsdabcsdabc

            n=0
            while [[ $string == *abc* ]]; do
            n=$(( n+1 ))
            string=$string/abc/ # remove first occurrence of "abc"
            done
            printf '%dn' "$n"


            This uses a while loop to remove the substring abc from the value in $string until no further occurrences of abc is found in $string, just as the second awk program above does.






            share|improve this answer

























            • Hi , Can u explain me on bash piece of code. not able to get how n will get value assigned to itself when we are just dealing with single line of input. Please help to explain line wise

              – Machine
              19 hours ago







            • 1





              @Machine I've explained it further now. The loop is looping until no abc is found in $string.

              – Kusalananda
              19 hours ago











            • string=$string/abc/ -- I never used this , so i believe this is inbuilt feature in unix.If u can elaborate more here

              – Machine
              19 hours ago






            • 1





              @Machine This is a bash-specific variable substitution that replaces the first occurrence abc in $string with nothing. The general form is $variable/pattern/word which replaces the first bit that matches pattern in $variable with word. Using $variable//pattern/word replaces all matches. This is described in the bash manual. It is a feature of the shell, not of Unix.

              – Kusalananda
              18 hours ago














            2












            2








            2







            Treating the string as consisting of fields that are delimited by abc:



            $ echo abcsdabcsdabc | awk -F 'abc' ' print NF - 1 '
            3


            The number of occurrences of the delimiter abc is 1 minus the number of fields that it delimits.



            $ echo abcsdabcsdabc | awk ' n=0; while (sub("abc", "")) n++; print n '
            3


            This deletes the substring abc from the line and counts the number of times this is done, then outputs that number. The n=0 is not needed if there is only one line of input.



            The gsub() function in awk returns the number of substitutions made, so the above could be simplified into



            $ echo abcsdabcsdabc | awk ' print gsub("abc", "") '
            3


            In bash, you can do the same thing as in that awk program that uses sub():



            string=abcsdabcsdabc

            n=0
            while [[ $string == *abc* ]]; do
            n=$(( n+1 ))
            string=$string/abc/ # remove first occurrence of "abc"
            done
            printf '%dn' "$n"


            This uses a while loop to remove the substring abc from the value in $string until no further occurrences of abc is found in $string, just as the second awk program above does.






            share|improve this answer















            Treating the string as consisting of fields that are delimited by abc:



            $ echo abcsdabcsdabc | awk -F 'abc' ' print NF - 1 '
            3


            The number of occurrences of the delimiter abc is 1 minus the number of fields that it delimits.



            $ echo abcsdabcsdabc | awk ' n=0; while (sub("abc", "")) n++; print n '
            3


            This deletes the substring abc from the line and counts the number of times this is done, then outputs that number. The n=0 is not needed if there is only one line of input.



            The gsub() function in awk returns the number of substitutions made, so the above could be simplified into



            $ echo abcsdabcsdabc | awk ' print gsub("abc", "") '
            3


            In bash, you can do the same thing as in that awk program that uses sub():



            string=abcsdabcsdabc

            n=0
            while [[ $string == *abc* ]]; do
            n=$(( n+1 ))
            string=$string/abc/ # remove first occurrence of "abc"
            done
            printf '%dn' "$n"


            This uses a while loop to remove the substring abc from the value in $string until no further occurrences of abc is found in $string, just as the second awk program above does.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 19 hours ago

























            answered 20 hours ago









            KusalanandaKusalananda

            136k17257426




            136k17257426












            • Hi , Can u explain me on bash piece of code. not able to get how n will get value assigned to itself when we are just dealing with single line of input. Please help to explain line wise

              – Machine
              19 hours ago







            • 1





              @Machine I've explained it further now. The loop is looping until no abc is found in $string.

              – Kusalananda
              19 hours ago











            • string=$string/abc/ -- I never used this , so i believe this is inbuilt feature in unix.If u can elaborate more here

              – Machine
              19 hours ago






            • 1





              @Machine This is a bash-specific variable substitution that replaces the first occurrence abc in $string with nothing. The general form is $variable/pattern/word which replaces the first bit that matches pattern in $variable with word. Using $variable//pattern/word replaces all matches. This is described in the bash manual. It is a feature of the shell, not of Unix.

              – Kusalananda
              18 hours ago


















            • Hi , Can u explain me on bash piece of code. not able to get how n will get value assigned to itself when we are just dealing with single line of input. Please help to explain line wise

              – Machine
              19 hours ago







            • 1





              @Machine I've explained it further now. The loop is looping until no abc is found in $string.

              – Kusalananda
              19 hours ago











            • string=$string/abc/ -- I never used this , so i believe this is inbuilt feature in unix.If u can elaborate more here

              – Machine
              19 hours ago






            • 1





              @Machine This is a bash-specific variable substitution that replaces the first occurrence abc in $string with nothing. The general form is $variable/pattern/word which replaces the first bit that matches pattern in $variable with word. Using $variable//pattern/word replaces all matches. This is described in the bash manual. It is a feature of the shell, not of Unix.

              – Kusalananda
              18 hours ago

















            Hi , Can u explain me on bash piece of code. not able to get how n will get value assigned to itself when we are just dealing with single line of input. Please help to explain line wise

            – Machine
            19 hours ago






            Hi , Can u explain me on bash piece of code. not able to get how n will get value assigned to itself when we are just dealing with single line of input. Please help to explain line wise

            – Machine
            19 hours ago





            1




            1





            @Machine I've explained it further now. The loop is looping until no abc is found in $string.

            – Kusalananda
            19 hours ago





            @Machine I've explained it further now. The loop is looping until no abc is found in $string.

            – Kusalananda
            19 hours ago













            string=$string/abc/ -- I never used this , so i believe this is inbuilt feature in unix.If u can elaborate more here

            – Machine
            19 hours ago





            string=$string/abc/ -- I never used this , so i believe this is inbuilt feature in unix.If u can elaborate more here

            – Machine
            19 hours ago




            1




            1





            @Machine This is a bash-specific variable substitution that replaces the first occurrence abc in $string with nothing. The general form is $variable/pattern/word which replaces the first bit that matches pattern in $variable with word. Using $variable//pattern/word replaces all matches. This is described in the bash manual. It is a feature of the shell, not of Unix.

            – Kusalananda
            18 hours ago






            @Machine This is a bash-specific variable substitution that replaces the first occurrence abc in $string with nothing. The general form is $variable/pattern/word which replaces the first bit that matches pattern in $variable with word. Using $variable//pattern/word replaces all matches. This is described in the bash manual. It is a feature of the shell, not of Unix.

            – Kusalananda
            18 hours ago


















            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%2f507368%2fcount-number-of-occurrences-of-a-pattern-on-same-line%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

            getting Checkpoint VPN SSL Network Extender working in the command lineHow to connect to CheckPoint VPN on Ubuntu 18.04LTS?Will the Linux ( red-hat ) Open VPNC Client connect to checkpoint or nortel VPN gateways?VPN client for linux machine + support checkpoint gatewayVPN SSL Network Extender in FirefoxLinux Checkpoint SNX tool configuration issuesCheck Point - Connect under Linux - snx + OTPSNX VPN Ububuntu 18.XXUsing Checkpoint VPN SSL Network Extender CLI with certificateVPN with network manager (nm-applet) is not workingWill the Linux ( red-hat ) Open VPNC Client connect to checkpoint or nortel VPN gateways?VPN client for linux machine + support checkpoint gatewayImport VPN config files to NetworkManager from command lineTrouble connecting to VPN using network-manager, while command line worksStart a VPN connection with PPTP protocol on command linestarting a docker service daemon breaks the vpn networkCan't connect to vpn with Network-managerVPN SSL Network Extender in FirefoxUsing Checkpoint VPN SSL Network Extender CLI with certificate

            Cannot Extend partition with GParted The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) 2019 Community Moderator Election ResultsCan't increase partition size with GParted?GParted doesn't recognize the unallocated space after my current partitionWhat is the best way to add unallocated space located before to Ubuntu 12.04 partition with GParted live?I can't figure out how to extend my Arch home partition into free spaceGparted Linux Mint 18.1 issueTrying to extend but swap partition is showing as Unknown in Gparted, shows proper from fdiskRearrange partitions in gparted to extend a partitionUnable to extend partition even though unallocated space is next to it using GPartedAllocate free space to root partitiongparted: how to merge unallocated space with a partition

            Marilyn Monroe Ny fiainany manokana | Jereo koa | Meny fitetezanafanitarana azy.