views:

498

answers:

2

I’m trying to write my first script to search for a given pattern in text file named test. Here is the script:

#! /bin/csh
 echo -n "enter pattern: "
  set pattern = $<
    foreach word (`cat test`)
         echo $word | egrep $pattern
    end

When I try to run it I get the message foreach: No match found. I suspect the problem is caused by (cat test). Any help would be much appreciated.

+1  A: 

does it have to be C shell...? you can learn to search files using awk

awk 'BEGIN{
 printf "Enter Pattern: "
 getline pattern < "-"
}
$0 ~ pattern{
    print 
}
' myfile
ghostdog74
yes unfortunately it does.
Mike55
ok problme solved. There must be white space after opening and before closing brackets.
Mike55
+1  A: 

@Pat - glad you've fixed it. Looping over the words in the file and running egrep over each one is a bit of an odd way to do it - I presume you're learning about C shell loops, rather than looking for the most succinct solution. You could match against the whole file in one go:

egrep "\b$pattern\b" test

The \b makes grep match on a word boundary.

You have my sympathy programming with csh - here's some food for thought: Csh Programming Considered Harmful.

martin clayton
Thanks Martin. This is a part of my coursework assignment and unfortunately we have to use C shell. As for the Csh Programming Considered Harmful I had read it already :).
Mike55