Script to count words matching pattern C shell
I wro开发者_如何学Cte this script which counts occurrences of particular pattern in a given file. However if text file contains square brackets or curly braces shell outputs a message "Missing }". Here is the script:
#!/bin/csh
@ count=0
foreach word ( `cat test` )
if (`echo $word | egrep -c 'int'`) then
@ count= $count + 1
endif
end
echo $count
You need to quote the expansion of word
: echo "$word"
.
If you just want to be able to count multiple occurrences on a single line (since grep -c
only counts lines that have at least one match), use tr
to change normal whitespace to newlines (then you can use grep -c
):
(tr ' \t' '\n\n' | fgrep -c int) < test
Also, scripting csh
is usually going to cause more problems than it is worth. Despite their own historical quirks, Bourne shells are much nicer to script. Go for dash
if you want to make sure your code is portable. Go with bash
, ksh
, or zsh
if you need more power.
csh% echo "foo \"bar\" \$ dollar"
csh: Unmatched ".
sh$ echo "foo \"bar\" \$ dollar"
foo "bar" $ dollar
精彩评论