Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Determine a word exits in a file

Status
Not open for further replies.

6656

Programmer
Nov 5, 2002
104
US
Hi, I want to determine a work if it exists in a file. I know that I have no the word in the file, but I get a true 'Yes' reture from below ksh code. Anyone can help me to fix it?

if [ `grep -w "$wd1" $file | wc -w` > 0 ]
then
echo 'Yes'
else
echo 'No word found'

Thanks,
Mike
 
You're getting the exit status of wc, not the exit status of grep.

Do something like
grep -s -w "$wd1" $file
or
grep -q -w "$wd1" $file

If you just want a yes/no answer from grep (via the exit status) as to whether something is found or not
 
Thanks Salem,

I got the same result using your code.

I think the happens due to I used 'for ... in .." loop.
If a filename is given, the return values of the file will return a numeric count value in below sample code. However, if the filename is assigned with more than one names or '*', the return counted values will like "filename1:0 filename2=4.....".

How to eliminate the filename in the return value?

==== sample code =======
for file in $filenames
do
if [ `grep -wisc "$wd1" $file` > 0 ]
then
echo " *****find $wd1 in the $file ***** "
else
echo 'No word found'
fi
done

Thanks again
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top