Programming logic help

Hi,

I was having a problem regarding this thread:

http://www.unix.com/shell-programming-scripting/225221-setting-variable-using-variables-loop.html

I have not been able to solve that issue. So i was thinking maybe my logic to solve the overall problem is wrong, so i am looking for a bit of help on what would be a good way to approach the following task.

I have a list of 24 files that are produced daily. On some days all 24 files may not be produced. The filenames are in the format filename-2digitnumber ( e.g. log-01). In each of the files, i need to search for an occurrence of a particular word and see how many times it occurs. Once i have the occurrences per file, i then need to total up all the occurrences per file into a grand total.

The way i have gone about this was to do a for loop, which had an if statement within it which did a check to see if the file existed. Then I would do a count on the file and assign it to a variable, that is also a variable. I get stuck at this stage as in the above thread. Code example:

file=log

for i in 01 02 03; do
if [ -f $file-$i ]; then
count$i=`grep -c word $file-$i`
fi
done

for i in 01 02 03; do 
if [ ! -z "$count$i" ]; then
:
else Tcount=`expr $Tcount + $count$i`
fi
done

Any ideas on how to go about this will be appreciated.

Thanks

How about this

for file in `ls -1 log-[0-9][0-9]`
do
    count=`grep -cw word $file|wc -l 2>/dev/null`
    [ -z "$count" ] && count=0
    sumcount=$(( $sumcount + $count ))
done

echo "Sum of count :$sumcount"

Nothing in your post indicates that you are using the per file counts for anything but calculation. If only the grand total is of interest:

cat log-* | grep -c word

If there are unwanted files in the directory that match log-*, you'll need to refine the pattern (possibly using more than one).

Regards,
Alister

---------- Post updated at 08:52 AM ---------- Previous update was at 08:47 AM ----------

That is never necessary and it will choke on filenames with IFS characters. The following is both safe and efficient:

for file in log-[0-9][0-9]

Regards,
Alister

1 Like