shell-script – Help with shell script and regular expressions

Question:

I'm making this shell script code that must go through each line of a text file, and determine if the sentence is positive or negative according to the IF condition

#!/usr/bin/ksh
file="${1}"

while read line;do

        pos=$(grep -oP ':\)|;\)|:D' $file | wc -l)   
        neg=$(grep -oP ':\('        $file | wc -l) 

if (( $pos * 2 > $neg * 5 )) ;then
   echo "Sentença Positiva "
else
   echo "Sentença Negativa"
fi

sleep 1
done <"$file"

But when I run the script on top of this text file: teste.txt

teste:) teste :) teste :) teste :)
teste:( teste :( teste :( teste :(

Instead of him returning:

Sentença Positiva
Sentença Negativa

it returns the two negatives:

Sentença Negativa
Sentença Negativa

How do I fix this problem?

Answer:

You are iterating through the file line by line with while read line;do , but grep the entire file. The following modification should fix this problem:

pos=$(echo "$line" | grep -oP ':\)|;\)|:D' | wc -l)
neg=$(echo "$line" | grep -oP ':\('        | wc -l)
Scroll to Top