foreach no match -C shell script
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.
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
@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.
精彩评论