How to scan a file for literal, return 0 or 1 if found?

How can i scan a file in a UNIX script and look for a particular keyword?

For example if i wanted to scan the file "lpcmp165.out" and see if it contains the term "error" or "ERROR" and then return a 0 or 1 or some indicator as such?

Detail example:
sqlplus -s xx/yyyyyyy#@zzz <<EOF > lpcmp165.out
set pagesize 0 feedback off verify off heading off echo off
set serveroutput on
DROP INDEX PKM_TCQ_DT_TPD_LOAN_EXLOAN_ID;
commit;
exit;
EOF

if [ lpcmp165.out contains "error" ] ; then <<<<< psuedo code
echo "bad result"
else
echo "good result"
fi

lpcmp165.out contains this output:
DROP INDEX xPKM_TCQ_DT_TPD_LOAN_EXLOAN_ID
*
ERROR at line 1:
ORA-01418: specified index does not exist

egrep "error|ERROR" lpcmp165.out 1>/dev/null 2>&1
mRetCode=$?
if [ $mRetCode -eq 0 ]; then
  echo 'Found'
else
  echo 'Not found'
fi

wow! thanks again ShellLife! works great!

can't say enough how helpful you've been over time, saved me many hours!

have a great week!

BobK

this site should hire you full time or set up some kind of Kudo's or donate button!

Thank you for your kind words, BobK. :slight_smile:

Our satisfaction is to see your problems resolved.

Take care!

ignore case -i option with grep

if [ `grep -i error filename 1>/dev/null 2>&1` -eq 0 ]
then
echo "found"
else
echo "not found"
fi

I think you meant

if grep -i error filename 1>/dev/null 2>&1
then
echo "found"
else
echo "not found"
fi

No !

with this

`grep -i error filename 2>/dev/null 1>&2` -eq 0

the return value of grep command is directly equated to the value 0

o - success pattern has been found
other value - pattern not found

Matrix,
Your solution:

if [ `grep -i error filename 1>/dev/null 2>&1` -eq 0 ]

does not work.

Kahuna is right in fixing your 'if' statement:

if grep -i error filename 1>/dev/null 2>&1

It is important to note that the option '-i' does not work as it
greps for more than just 'error' and 'ERROR':
'Error', 'eRROR', 'ErRoR', or any other combination of mixed cases.

The code does not work as written. Please try to run it. The return value from grep will not be used in the if statement. Perhaps you meant to add a "-c"?

I accept ! :slight_smile:

cat test2
pattern
grep -i pattern test2
if [ $? -eq 0 ]
then
  echo "found"
else
  echo "not found"
fi
if grep pattern test2 1>/dev/null 2>&1
then
  echo "found"
else 
  echo "not found"
fi

based on success or failure of the grep command

FWIW:
use grep -q to suppress output:

grep -q 'some string' myfile ; echo $(( ! $? ))

will show 1 if found and 0 if not found - ksh and bash.