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

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!

2 Answers

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
3

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

#!/usr/bin/env bash
set -e
set -x
while read -r linenum line
do if [ "$line" = "I am good with programming in C, but beginner in shell" ] then # Process things here echo "same" fi
done < "$1"

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:

  • -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
  • linenum: variable that holds the line numbers when bash splits the read lines into two variables while the other is passed in via the lin variable.
7

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like