Operating System - HP-UX
1823988 Members
4022 Online
109667 Solutions
New Discussion

How to fasten nested "for" loops

 
SOLVED
Go to solution
allanm77
Frequent Advisor

How to fasten nested "for" loops

Hey All,

 

I have a script/command which has a for loop nested inside of another for loop -

 

for i in `cat file1`; do echo "$i******"; for j in `cat file2`; do command $i arg1  |grep $j; done; done

 

file1

APP1

APP2

..

 

file2

library1

library2

..

 

command = libinfo APP1

output of the command list all libraries for APP1, but I want to grep for only the ones given in file2.

 

How can fasten this up?

 

Thanks,

Allan.

5 REPLIES 5
James R. Ferguson
Acclaimed Contributor

Re: How to fasten nested "for" loops


@allanm77 wrote:

I have a script/command which has a for loop nested inside of another for loop -

 

for i in `cat file1`; do echo "$i******"; for j in `cat file2`; do command $i arg1  |grep $j; done; done

...

output of the command list all libraries for APP1, but I want to grep for only the ones given in file2.

 

How can fasten this up?


I suppose by "fasten this up" you mean "make faster".

 

That said, you could use :

 

#!/usr/bin/sh
while read i
do 
     echo "$i******"
     command $i arg1 | grep -f file2
done < file1

Look at the manpages for 'grep'.  With '-f pattern_file' the regular expression (grep and grep -E) or strings list (grep -F) is taken from the pattern_file.

 

Regards!

 

...JRF...

Dennis Handly
Acclaimed Contributor
Solution

Re: How to speed up nested grep "for" loops

>I suppose by "fasten this up" you mean "make faster".

 

Or "speed up".  :-)

 

>With '-f pattern_file'

 

Right, using vector methods.

 

Also, you don't have to use while, for loops also take infinite args but they all have to be read into memory:

for i in $(< file1); do

   echo "$i******"

   command $i arg1 | grep -f file2

done

 

If command takes a list of arguments, you may be able to invoke command once as in nm(1):

nm -pxAN $(< file1) | fgrep -f file2

allanm77
Frequent Advisor

Re: How to fasten nested "for" loops

Thanks Dennis!
James R. Ferguson
Acclaimed Contributor

Re: How to fasten nested "for" loops

Hi (again) :

 

And what was wrong with the substance of the answer I provided --- the use of 'grep -f' ?

 

Both of us, too, eliminated your useless 'cat'.   Did you notice that either?

 

...JRF...

allanm77
Frequent Advisor

Re: How to fasten nested "for" loops

Totally missed, thanks!