Reputation: 24423
I need to check if a variable can be found somewhere within a file (matching the exact line from beginning to end), e.g.:
if [ "$find" is in file.txt ]
then
echo "Found."
else
echo "Not found."
fi
I have been using grep -c '^$find$' > count.txt
, then count="$(cat count.txt)"
, then checking if $count
is greater than "0", but this method seems inefficient.
What is the simplest way to check if a variable is found, in its entirely, as a line somewhere within a file?
Upvotes: 1
Views: 663
Reputation: 123608
Use grep
:
grep -q "$find" file.txt && echo "Found." || echo "Not found."
If you want to match the entire line, use the -x
option:
grep -xq "$find" file.txt && echo "Found." || echo "Not found."
Quoting man grep
:
-q, --quiet, --silent
Quiet; do not write anything to standard output. Exit immedi-
ately with zero status if any match is found, even if an error
was detected. Also see the -s or --no-messages option.
-x, --line-regexp
Select only those matches that exactly match the whole line.
The above can also be written as:
if grep -xq "$find" file.txt; then
echo "Found."
else
echo "Not found."
fi
Upvotes: 6