LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   grep fails in shell script when string is not found (https://www.linuxquestions.org/questions/linux-newbie-8/grep-fails-in-shell-script-when-string-is-not-found-878678/)

coolnfunky 05-03-2011 09:42 PM

grep fails in shell script when string is not found
 
Hello

I am having trouble using grep command. I want to search for each line in first file in second file and if they are present, write to file called successfile else to failfile. Below is the code

what is happening is, when the first failure occurs (when a line in first file is not present in second file), the script is killed.

Can anyone please tell me what I am doing wrong?

Code:

        while read line
        do
                temp=""
                if [ "$line" != "" ]
                then
                        grep $line $pwdir/$file
                        if [ "$?" == "0" ]
                        then
                                successcount=$successcount+1
                                echo $line>>$successfile
                        else
                                echo "fail >>>>>>> $line"
                                failcount=$failcount+1
                                echo $line>>$failfile
                        fi
                fi
        done < "$kwd_file"


j1alu 05-03-2011 11:00 PM

I think (!) you want:
a) grep $line $pwdir/$file
use quotes around $line, else you run into trouble if it read reads more than one string in a line.

b) successcount=$successcount+1
use
Code:

((successcount=$successcount))
to get an integer value.

c) echo $line>>successfile
put spaces around the redirection:
Code:

echo $line >> successfile
As far i see that should work.

You can also consider to do it like this:
Code:

if grep "$line" $pwdir/$file
instead of:
grep $line $pwdir/$file
if [ "$?" == "0" ]
grep gives an exit code, either success or failure. "if" uses it.

grail 05-03-2011 11:01 PM

Well looking at your code I am guessing the first file has blank lines?
You create a variable temp that is never used.

To answer your questions though, use you grep in the if:
Code:

if grep -q $line $pwdir/$file
-q will stop output being sent to the screen for each search which I presume would not be required.

coolnfunky 05-04-2011 12:50 AM

Thanks for the quick responses. I have incorporated all of your suggestions. The script is working as expected. Thanks much!!

grail 05-04-2011 10:02 AM

I would add that you can use normal increment (like C) in bash as well:
Code:

(( successcount++ ))


All times are GMT -5. The time now is 11:53 PM.