How to use Grep properly?

Hi Forum

Im making a script that takes multiple unix users and lists the users and the groups that the user is part of. the grouplist looks like this

grouplst="example_group1|example_group2|example_group3|example_group4"

I got most of it working but Im having trouble with a while loop that im using to filter out groups that dont matter.

 
        cntr3=1
        tempgrplst=$grouplist
        FilterIDgroups=""
        while (($cntr <= $groupcnt))
        do
                currentgroup=$(print $tempgrplst|awk -F '|' '{print $1}')
                cntr=$(($cntr + 1))
                print $IDgroups | grep $currentgroup >> $FilterIDgroups
                tempgrplst=${tempgrplst#*\|}
        done

I am trying to get only the groups that are in the grouplist to be in the variable FilterIDgroups. Sorry the variable names are bad, I had to change them to post them online.

Alas you are leaving out the essential part - the contents of IDgroups . And, I'm nor sure I understand the underlying logics. Do you want a "logical AND" of the two group lists: grouplist and IDgroups?

BTW, the redirection >> $FilterIDgroups will fail as you assigned the empty string to FilterIDgroups.

---------- Post updated at 17:05 ---------- Previous update was at 17:02 ----------

And, you could eliminate a big portion of your code snippet by using an array:

IFS="|" grouparr=($grouplst )
while (( cntr < ${#grouparr[@]} )); do echo ${grouparr[((cntr++))]}, $cntr; done

And, you're assigning cntr3 but using cntr .

the content of the IDgroups looks like this

memberOf: CN=example_group,OU=CL,OU=LOB,DC=prod,DC=test,DC=net
memberOf: CN=example_group2,OU=CL,OU=LOB,DC=prod,DC=test,DC=net

the cntr thing was a mistake when i was changing the variables for the forum.

also am I missing something with the array suggestion you gave me

        
        IFS="|" grouparr=($grouplst )
        while(( cntr < ${#grouparr[@]} ));
        do
                echo ${grouparr[((cntr++))]}, $cntr;
                currgrp=$(print $tempgrplst|awk -F '|' '{print $1}')
                tempgrplst=${tempgrplst#*\|}
        done

You don't need currgrp any more - it's the grouparr[cntr] array element!

But - even if I still don't understand exactly what you're after, I still think all of this can be done with one single awk script.

Another proposal that does not need a loop

IDgroups="\
memberOf: CN=example_group,OU=CL,OU=LOB,DC=prod,DC=test,DC=net
memberOf: CN=example_group2,OU=CL,OU=LOB,DC=prod,DC=test,DC=net"
grouplst="example_group1|example_group2|example_group3|example_group4"

printf "%s\n" "$IDgroups" | egrep "CN=($grouplst)," > $FilterIDgroups

If $IDgroups is a filename, change the latter to

egrep "CN=($grouplst)," < $IDgroups > $FilterIDgroups