Lets say I have a file containing string patterns to be looked for inside a file.
I would normaly do :
grep -if MyFilePattern FiletoSearchInto
if I use the -c it gives how many total lines it found out of my whole pattern file, but what if i want grep to report how many times it found each records in the MyFilePattern file ?
This is to help me at my job to make sure whenever I do this, that I would either find each lines once or none at all. If one line is there more then once, then I have a problem that I must fix.
The -q option of grep means "quiet": with this option grep gives a returncode 0 if it found the pattern and 1 of not. Additionally one doesn't have to get rid of the output as there is none. To use grep -q in a compound command use
if [ $(InputStream | grep -q "pattern" ; print - $?) -eq 0 ] ; then
# pattern found
else
# pattern not found
fi
Here is a little script, which accepts a filename and a pattern (in principle any regexp should work, but i haven't tested it with more complicated ones - there may arise problems with the shell interpreting it in this case) and prints out the number of occurrences:
#!/bin/ksh
fIn="$1"
chPattern="$2"
iFound=0
cat $fIn | while read chLine ; do
while [ $(print - $chLine | grep -c "$chPattern") -gt 0 ] ; do
chLine="$(print - "$chLine" | sed 's/'"$chPattern"'//')"
(( iFound += 1 ))
done
done
print - "Occurrences: $iFound"
The script makes use of a certain feature of sed: to change only the first ocurrence of the pattern in a substitute-operation, as long as the g-clause is not given. The command
print - "pattern pattern pattern" | sed '/pattern/newpattern/'
will only change the first occurrence of "pattern", to change all one would have to write:
print - "pattern pattern pattern" | sed '/pattern/newpattern/g'
The inner loop "chops off" one occurrence of pattern after the other, until none is left. For every chop-off-operation a counter is increased.