shell-script – Help with shell script and regular expressions


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


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 "
   echo "Sentença Negativa"

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?


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