jeudi 25 février 2016

While read line with grep

I am trying to report lines found using grep and while.

I know you can use the following to compare a list of strings from inputs.txt and find them in your target file like so:

grep -f inputs.txt file_to_check

What I want is to read each line of the inputted strings and grep them individual in a loop.

So I have tried the following methods:

cat inputs.txt | while read line; do if grep "$line" filename_to_check; then echo "found"; else echo "not found"; fi; done

This returns nothing when I redirect the output to a file.

while read line
do
if grep "$line" file_to_check
  then echo "found"
else 
  echo "not found"
fi
done < inputs.txt

Same as the first one but from what I found is better to do.

I know it iterates line by line because I can replace grep with echo $line and it prints each line; but either method doesn't return anything like grep -f above, instead it shows:

not found
not found
not found
.
. etc.

So what I'm looking for is something where it will iterate through each line and check it via grep using an if statement to determine if grep has actually found it or not. I know I may not have all proper logic but the output for what I want should look something like:

Found *matching line in file_to_check* 
Found *matching line in file_to_check*
Not Found $line *(string that does not match)*
.
. etc.

Aucun commentaire:

Enregistrer un commentaire