save every line in log file with matched string

i have been doing this script to match every line in a current log file (access_log) with strings that i list from a path (consist of 100 of user's name ex: meggae )..
and then make a directory of every string from the text file (/path/meggae/) --->if it matched..
then print every line from the log file if it matched the string into a new file name base on the string (meggae.txt) in the new created directory (/path/meggae/meggae.txt)..

below is the example script that i made..it has no error so far but it uses 100% of my processes as well as my memory and sometimes it uses my swap space and my lappy go lagged and hang..i hope some explanation and some solution can help me not to crash my dear lappy :confused:

any solutions will tremendously help me with this space/memory crashing and what have i done wrong :confused:

Too many un-necessary nested foreach. From what I can see, the outer foreach for each entry in password and the inner foreach for each line in cisco is sufficient. Why do you have to repeatedly keep doing foreach even for opening and closing files?

What do you mean by "foreach ($line =~ $string)"? Why can't you write it as "if($line =~ $string)" and do what you need to do within the if block?

There are many other issues but you may want to sort out the above problems first and see if that makes the process less demanding.

Here's a way you could do it in ksh.. not the most efficient way, but worth a shot to see if it eats up your system resources as badly as your method..

#!/bin/ksh

logfile=/path/to/logfile
namelist=/path/to/namelist
outputdir=/output/dir


cat $namelist | while read name
do

   grep $name $logfile > temp
   if [ $(cat temp | wc -l) -ne 0 ];then 
    
     mkdir  ${outputdir}/$name
     cat temp > ${outputdir}/$name
     cat temp > ${outputdir}/${name}/${name}.txt
       
    fi

done

rikxik..
thanks for the brilliant suggestion given..i also thought the problem might be with the programming (foreach statement) as i'm not into much of the programming..
i've review the code and cut out the unnecessary loop..it works and it works great if i execute it from the terminal instead of browser..
thanks insamniac for ur ksh opinion..i would really like to consider it but i don't really have much time now to learn new things..but i currently trying the code already..it surely gives me another sight way of solving coming problems..