tags:

views:

419

answers:

1

I wrote 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
+3  A: 

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
Chris Johnsen
That is exactly what I need Chris. I was trying to achieve that by using for loop to split each line into one word lines, than use egrep, but tr command seems to be much easier. This is my first script, and unfortunately I have to use C shell, as this is the one they use at uni. In the future I definitely switch to bash or korn.
Mike55
Even if your login shell is `csh`, you can still write scripts in other shells/languages. If you have not been told that you must use `csh` for scripts then you should be able to find a Bourne shell as `/bin/sh` on any Unix-oid system installed in the last two decades. If, for whatever reason, you end up stuck writing scripts in `csh` check out that link I included in my answer, it could help you avoid problem areas and/or help keep you from getting stumped by something that is completely impossible in `csh`.
Chris Johnsen
They asked us to write all scripts in C shell, because lecture notes were written for C, however we need to explain what code needs to be changed to make it work on bash.
Mike55