LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   "searching for a matching pattern" (http://www.linuxquestions.org/questions/programming-9/searching-for-a-matching-pattern-617904/)

sharath.bv 02-01-2008 05:52 AM

"searching for a matching pattern"
 
hi,

i am trying to search for a particular word form a file.
My code is not working. Please help

------------------------------------------
cat filename | while read line
do
for i in $line ;do
if [ "i" == "world" ]; then
echo "found"
fi
done
done

---------------------------------------------
Here i am first reading a line and then comparing each world of the line with the word "world".

Guttorm 02-01-2008 06:03 AM

Hi

You are missing a $ before i:

if [ "$i" == "world" ]; then
...

And by the way, why not use grep?

sharath.bv 02-01-2008 06:12 AM

thanks for reply.....now my code is working :)

pixellany 02-01-2008 06:18 AM

Quote:

cat filename | while read line
Does this work? A pipe is used to pass output to a command that expects input. I don't know what it means to pass data to the "while" command.

"read" means get data from standard input (the keyboard unless changed)

Quote:

for i in $line; do
..
done
This only loops once (if at all). The "i in" construct has to be followed by something that produces a list of values.

ghostdog74 02-01-2008 06:23 AM

Quote:

Originally Posted by pixellany (Post 3042283)
Does this work?

yes it does. The "better" way is to skin the cat totally.
Code:

while read -r line
do
  # blah
done < "file"


trashbird1240 02-01-2008 08:06 AM

Why are you using this instead of grep?

Joel

KenJackson 02-02-2008 11:24 AM

Two people have already asked about grep, so forgive me, but I just can't help but suggest this:

grep -wq world filename && echo found


All times are GMT -5. The time now is 08:54 AM.