How do I read line by line in a file using while loop, and in each iteration, grep each line to compare to a...











up vote
2
down vote

favorite












I have a file called abc.txt with the contents as follows:



1: It is a shell script
2: There are few lines in this file
3: I am good with programming in C, but beginner in shell
4: We are going towards end of file
5: END OF FILE


I want to read each of the file iteratively, and in each iteration I want to compare the line with "I am good with programming in C, but beginner in shell", and then do some processing.



Any help would be greatly appreciated. Thanks!










share|improve this question


























    up vote
    2
    down vote

    favorite












    I have a file called abc.txt with the contents as follows:



    1: It is a shell script
    2: There are few lines in this file
    3: I am good with programming in C, but beginner in shell
    4: We are going towards end of file
    5: END OF FILE


    I want to read each of the file iteratively, and in each iteration I want to compare the line with "I am good with programming in C, but beginner in shell", and then do some processing.



    Any help would be greatly appreciated. Thanks!










    share|improve this question
























      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      I have a file called abc.txt with the contents as follows:



      1: It is a shell script
      2: There are few lines in this file
      3: I am good with programming in C, but beginner in shell
      4: We are going towards end of file
      5: END OF FILE


      I want to read each of the file iteratively, and in each iteration I want to compare the line with "I am good with programming in C, but beginner in shell", and then do some processing.



      Any help would be greatly appreciated. Thanks!










      share|improve this question













      I have a file called abc.txt with the contents as follows:



      1: It is a shell script
      2: There are few lines in this file
      3: I am good with programming in C, but beginner in shell
      4: We are going towards end of file
      5: END OF FILE


      I want to read each of the file iteratively, and in each iteration I want to compare the line with "I am good with programming in C, but beginner in shell", and then do some processing.



      Any help would be greatly appreciated. Thanks!







      command-line grep






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 8 hours ago









      ShellyBelly

      556




      556






















          2 Answers
          2






          active

          oldest

          votes

















          up vote
          6
          down vote













          Using a shell loop is unnecessary, as grep already iterates over lines:



          grep '^[0-9]:  I am good with programming in C, but beginner in shell' input.txt


          If there's a matching line, it will be printed. [0-9] defines range of characters that will be matched. We can also extend that to longer numbers [0-9]*: (and I think with perl regex -P option that could be done as [0-9]+:).



          If a shell loop is really necessary, we can use case statement for pattern matching



          while IFS= read -r line; do
          case $line in
          *": I am good with programming in C") echo "Matched: $line";;
          esac
          done < input.xt





          share|improve this answer






























            up vote
            5
            down vote













            Try this sample code to help identify and modify to suit your needs:



            #!/usr/bin/env bash
            set -e
            set -x

            cut -d" " -f2- "$1" | while IFS= read -r line
            do
            if [ "$line" = "I am good with programming in C, but beginner in shell" ]
            then
            # Process things here
            echo "same"
            fi
            done


            Usage:





            • Make executable:



              chmod +x script.sh



            • Place script in any folder then run script by passing a file to it:



              ./script.sh /path/to/data.txt



            Info:





            • cut -d" " -f2- "$1" |: Removes the leading line numbers and passes the results to the while loop.


            • IFS=: Option before read command to prevent leading/trailing whitespace from being trimmed.


            • -r: Option passed to read command prevents backslash escapes from being interpreted.


            • set -e: Bash option to stop script on first error.
              -set -x: Bash option used to debug the scrtip.


            • "$1": The file variable passed to the script in this case data.txt






            share|improve this answer



















            • 1




              @George So you're using -d" " to split on whitespace and cut all lines starting from the second one. I'd suggest another way: while IFS= read -r linenum line. The shell will perform wordsplitting on the input line and place first item ( line numbers ) into linenum variable, but all other things will go into line variable. Aside from other things, case statement can be used as alternative to [[ comparison.
              – Sergiy Kolodyazhnyy
              7 hours ago










            • Can I implement this script in #!/bin/sh ?
              – ShellyBelly
              7 hours ago










            • @AkshayNandi Yes, but you need to change [[ to [ because [[ is specific to bash. See my answer for portable solution
              – Sergiy Kolodyazhnyy
              7 hours ago










            • @SergiyKolodyazhnyy I tried that it didn't do so on the word splitting.
              – George Udosen
              6 hours ago










            • @GeorgeUdosen Oh ? Interesting. What was the output you were getting ? Were you still using cut ? Because if you just use the loop I suggested, you can drop cut from the script
              – Sergiy Kolodyazhnyy
              6 hours ago











            Your Answer








            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "89"
            };
            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',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            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%2faskubuntu.com%2fquestions%2f1098445%2fhow-do-i-read-line-by-line-in-a-file-using-while-loop-and-in-each-iteration-gr%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








            up vote
            6
            down vote













            Using a shell loop is unnecessary, as grep already iterates over lines:



            grep '^[0-9]:  I am good with programming in C, but beginner in shell' input.txt


            If there's a matching line, it will be printed. [0-9] defines range of characters that will be matched. We can also extend that to longer numbers [0-9]*: (and I think with perl regex -P option that could be done as [0-9]+:).



            If a shell loop is really necessary, we can use case statement for pattern matching



            while IFS= read -r line; do
            case $line in
            *": I am good with programming in C") echo "Matched: $line";;
            esac
            done < input.xt





            share|improve this answer



























              up vote
              6
              down vote













              Using a shell loop is unnecessary, as grep already iterates over lines:



              grep '^[0-9]:  I am good with programming in C, but beginner in shell' input.txt


              If there's a matching line, it will be printed. [0-9] defines range of characters that will be matched. We can also extend that to longer numbers [0-9]*: (and I think with perl regex -P option that could be done as [0-9]+:).



              If a shell loop is really necessary, we can use case statement for pattern matching



              while IFS= read -r line; do
              case $line in
              *": I am good with programming in C") echo "Matched: $line";;
              esac
              done < input.xt





              share|improve this answer

























                up vote
                6
                down vote










                up vote
                6
                down vote









                Using a shell loop is unnecessary, as grep already iterates over lines:



                grep '^[0-9]:  I am good with programming in C, but beginner in shell' input.txt


                If there's a matching line, it will be printed. [0-9] defines range of characters that will be matched. We can also extend that to longer numbers [0-9]*: (and I think with perl regex -P option that could be done as [0-9]+:).



                If a shell loop is really necessary, we can use case statement for pattern matching



                while IFS= read -r line; do
                case $line in
                *": I am good with programming in C") echo "Matched: $line";;
                esac
                done < input.xt





                share|improve this answer














                Using a shell loop is unnecessary, as grep already iterates over lines:



                grep '^[0-9]:  I am good with programming in C, but beginner in shell' input.txt


                If there's a matching line, it will be printed. [0-9] defines range of characters that will be matched. We can also extend that to longer numbers [0-9]*: (and I think with perl regex -P option that could be done as [0-9]+:).



                If a shell loop is really necessary, we can use case statement for pattern matching



                while IFS= read -r line; do
                case $line in
                *": I am good with programming in C") echo "Matched: $line";;
                esac
                done < input.xt






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited 6 hours ago









                dessert

                21.5k55896




                21.5k55896










                answered 7 hours ago









                Sergiy Kolodyazhnyy

                68.2k9142302




                68.2k9142302
























                    up vote
                    5
                    down vote













                    Try this sample code to help identify and modify to suit your needs:



                    #!/usr/bin/env bash
                    set -e
                    set -x

                    cut -d" " -f2- "$1" | while IFS= read -r line
                    do
                    if [ "$line" = "I am good with programming in C, but beginner in shell" ]
                    then
                    # Process things here
                    echo "same"
                    fi
                    done


                    Usage:





                    • Make executable:



                      chmod +x script.sh



                    • Place script in any folder then run script by passing a file to it:



                      ./script.sh /path/to/data.txt



                    Info:





                    • cut -d" " -f2- "$1" |: Removes the leading line numbers and passes the results to the while loop.


                    • IFS=: Option before read command to prevent leading/trailing whitespace from being trimmed.


                    • -r: Option passed to read command prevents backslash escapes from being interpreted.


                    • set -e: Bash option to stop script on first error.
                      -set -x: Bash option used to debug the scrtip.


                    • "$1": The file variable passed to the script in this case data.txt






                    share|improve this answer



















                    • 1




                      @George So you're using -d" " to split on whitespace and cut all lines starting from the second one. I'd suggest another way: while IFS= read -r linenum line. The shell will perform wordsplitting on the input line and place first item ( line numbers ) into linenum variable, but all other things will go into line variable. Aside from other things, case statement can be used as alternative to [[ comparison.
                      – Sergiy Kolodyazhnyy
                      7 hours ago










                    • Can I implement this script in #!/bin/sh ?
                      – ShellyBelly
                      7 hours ago










                    • @AkshayNandi Yes, but you need to change [[ to [ because [[ is specific to bash. See my answer for portable solution
                      – Sergiy Kolodyazhnyy
                      7 hours ago










                    • @SergiyKolodyazhnyy I tried that it didn't do so on the word splitting.
                      – George Udosen
                      6 hours ago










                    • @GeorgeUdosen Oh ? Interesting. What was the output you were getting ? Were you still using cut ? Because if you just use the loop I suggested, you can drop cut from the script
                      – Sergiy Kolodyazhnyy
                      6 hours ago















                    up vote
                    5
                    down vote













                    Try this sample code to help identify and modify to suit your needs:



                    #!/usr/bin/env bash
                    set -e
                    set -x

                    cut -d" " -f2- "$1" | while IFS= read -r line
                    do
                    if [ "$line" = "I am good with programming in C, but beginner in shell" ]
                    then
                    # Process things here
                    echo "same"
                    fi
                    done


                    Usage:





                    • Make executable:



                      chmod +x script.sh



                    • Place script in any folder then run script by passing a file to it:



                      ./script.sh /path/to/data.txt



                    Info:





                    • cut -d" " -f2- "$1" |: Removes the leading line numbers and passes the results to the while loop.


                    • IFS=: Option before read command to prevent leading/trailing whitespace from being trimmed.


                    • -r: Option passed to read command prevents backslash escapes from being interpreted.


                    • set -e: Bash option to stop script on first error.
                      -set -x: Bash option used to debug the scrtip.


                    • "$1": The file variable passed to the script in this case data.txt






                    share|improve this answer



















                    • 1




                      @George So you're using -d" " to split on whitespace and cut all lines starting from the second one. I'd suggest another way: while IFS= read -r linenum line. The shell will perform wordsplitting on the input line and place first item ( line numbers ) into linenum variable, but all other things will go into line variable. Aside from other things, case statement can be used as alternative to [[ comparison.
                      – Sergiy Kolodyazhnyy
                      7 hours ago










                    • Can I implement this script in #!/bin/sh ?
                      – ShellyBelly
                      7 hours ago










                    • @AkshayNandi Yes, but you need to change [[ to [ because [[ is specific to bash. See my answer for portable solution
                      – Sergiy Kolodyazhnyy
                      7 hours ago










                    • @SergiyKolodyazhnyy I tried that it didn't do so on the word splitting.
                      – George Udosen
                      6 hours ago










                    • @GeorgeUdosen Oh ? Interesting. What was the output you were getting ? Were you still using cut ? Because if you just use the loop I suggested, you can drop cut from the script
                      – Sergiy Kolodyazhnyy
                      6 hours ago













                    up vote
                    5
                    down vote










                    up vote
                    5
                    down vote









                    Try this sample code to help identify and modify to suit your needs:



                    #!/usr/bin/env bash
                    set -e
                    set -x

                    cut -d" " -f2- "$1" | while IFS= read -r line
                    do
                    if [ "$line" = "I am good with programming in C, but beginner in shell" ]
                    then
                    # Process things here
                    echo "same"
                    fi
                    done


                    Usage:





                    • Make executable:



                      chmod +x script.sh



                    • Place script in any folder then run script by passing a file to it:



                      ./script.sh /path/to/data.txt



                    Info:





                    • cut -d" " -f2- "$1" |: Removes the leading line numbers and passes the results to the while loop.


                    • IFS=: Option before read command to prevent leading/trailing whitespace from being trimmed.


                    • -r: Option passed to read command prevents backslash escapes from being interpreted.


                    • set -e: Bash option to stop script on first error.
                      -set -x: Bash option used to debug the scrtip.


                    • "$1": The file variable passed to the script in this case data.txt






                    share|improve this answer














                    Try this sample code to help identify and modify to suit your needs:



                    #!/usr/bin/env bash
                    set -e
                    set -x

                    cut -d" " -f2- "$1" | while IFS= read -r line
                    do
                    if [ "$line" = "I am good with programming in C, but beginner in shell" ]
                    then
                    # Process things here
                    echo "same"
                    fi
                    done


                    Usage:





                    • Make executable:



                      chmod +x script.sh



                    • Place script in any folder then run script by passing a file to it:



                      ./script.sh /path/to/data.txt



                    Info:





                    • cut -d" " -f2- "$1" |: Removes the leading line numbers and passes the results to the while loop.


                    • IFS=: Option before read command to prevent leading/trailing whitespace from being trimmed.


                    • -r: Option passed to read command prevents backslash escapes from being interpreted.


                    • set -e: Bash option to stop script on first error.
                      -set -x: Bash option used to debug the scrtip.


                    • "$1": The file variable passed to the script in this case data.txt







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited 6 hours ago

























                    answered 8 hours ago









                    George Udosen

                    18.7k94265




                    18.7k94265








                    • 1




                      @George So you're using -d" " to split on whitespace and cut all lines starting from the second one. I'd suggest another way: while IFS= read -r linenum line. The shell will perform wordsplitting on the input line and place first item ( line numbers ) into linenum variable, but all other things will go into line variable. Aside from other things, case statement can be used as alternative to [[ comparison.
                      – Sergiy Kolodyazhnyy
                      7 hours ago










                    • Can I implement this script in #!/bin/sh ?
                      – ShellyBelly
                      7 hours ago










                    • @AkshayNandi Yes, but you need to change [[ to [ because [[ is specific to bash. See my answer for portable solution
                      – Sergiy Kolodyazhnyy
                      7 hours ago










                    • @SergiyKolodyazhnyy I tried that it didn't do so on the word splitting.
                      – George Udosen
                      6 hours ago










                    • @GeorgeUdosen Oh ? Interesting. What was the output you were getting ? Were you still using cut ? Because if you just use the loop I suggested, you can drop cut from the script
                      – Sergiy Kolodyazhnyy
                      6 hours ago














                    • 1




                      @George So you're using -d" " to split on whitespace and cut all lines starting from the second one. I'd suggest another way: while IFS= read -r linenum line. The shell will perform wordsplitting on the input line and place first item ( line numbers ) into linenum variable, but all other things will go into line variable. Aside from other things, case statement can be used as alternative to [[ comparison.
                      – Sergiy Kolodyazhnyy
                      7 hours ago










                    • Can I implement this script in #!/bin/sh ?
                      – ShellyBelly
                      7 hours ago










                    • @AkshayNandi Yes, but you need to change [[ to [ because [[ is specific to bash. See my answer for portable solution
                      – Sergiy Kolodyazhnyy
                      7 hours ago










                    • @SergiyKolodyazhnyy I tried that it didn't do so on the word splitting.
                      – George Udosen
                      6 hours ago










                    • @GeorgeUdosen Oh ? Interesting. What was the output you were getting ? Were you still using cut ? Because if you just use the loop I suggested, you can drop cut from the script
                      – Sergiy Kolodyazhnyy
                      6 hours ago








                    1




                    1




                    @George So you're using -d" " to split on whitespace and cut all lines starting from the second one. I'd suggest another way: while IFS= read -r linenum line. The shell will perform wordsplitting on the input line and place first item ( line numbers ) into linenum variable, but all other things will go into line variable. Aside from other things, case statement can be used as alternative to [[ comparison.
                    – Sergiy Kolodyazhnyy
                    7 hours ago




                    @George So you're using -d" " to split on whitespace and cut all lines starting from the second one. I'd suggest another way: while IFS= read -r linenum line. The shell will perform wordsplitting on the input line and place first item ( line numbers ) into linenum variable, but all other things will go into line variable. Aside from other things, case statement can be used as alternative to [[ comparison.
                    – Sergiy Kolodyazhnyy
                    7 hours ago












                    Can I implement this script in #!/bin/sh ?
                    – ShellyBelly
                    7 hours ago




                    Can I implement this script in #!/bin/sh ?
                    – ShellyBelly
                    7 hours ago












                    @AkshayNandi Yes, but you need to change [[ to [ because [[ is specific to bash. See my answer for portable solution
                    – Sergiy Kolodyazhnyy
                    7 hours ago




                    @AkshayNandi Yes, but you need to change [[ to [ because [[ is specific to bash. See my answer for portable solution
                    – Sergiy Kolodyazhnyy
                    7 hours ago












                    @SergiyKolodyazhnyy I tried that it didn't do so on the word splitting.
                    – George Udosen
                    6 hours ago




                    @SergiyKolodyazhnyy I tried that it didn't do so on the word splitting.
                    – George Udosen
                    6 hours ago












                    @GeorgeUdosen Oh ? Interesting. What was the output you were getting ? Were you still using cut ? Because if you just use the loop I suggested, you can drop cut from the script
                    – Sergiy Kolodyazhnyy
                    6 hours ago




                    @GeorgeUdosen Oh ? Interesting. What was the output you were getting ? Were you still using cut ? Because if you just use the loop I suggested, you can drop cut from the script
                    – Sergiy Kolodyazhnyy
                    6 hours ago


















                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Ask Ubuntu!


                    • 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.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • 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%2faskubuntu.com%2fquestions%2f1098445%2fhow-do-i-read-line-by-line-in-a-file-using-while-loop-and-in-each-iteration-gr%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

                    Catalogne

                    Violoncelliste

                    Héron pourpré