Concatenate Loop Results

Hi,

I have the following situation:

Param1Values = AAAA,BBBB
 
Param1=$(echo $Param1Values| tr "," "\n")
for x in $Param1
do
    db2 select X from Y where Z IN ('$x')
done

Obviously the above will perform the select 'x' amount of times.

Is there a way in which i can concatanate the results of the loop into one string, so i can perform the select statement once?

So currently i will have:

db2 select X from Y where Z IN ('AAAA')
db2 select X from Y where Z IN ('BBBB')
 

Is there a way in which manipulating the above will result in:

db2 select X from Y where Z IN ('AAAA','BBBB')

NOTE: Param1Values will not have a set amount of values i.e. it wont always be 2 parameters, it can be different everytime.

Cheers

Something like:

Param1Values="AAAA,BBBB"

x=$(echo $Param1Values | sed "s/\(.*\),\(.*\)/'\1','\2'/")
db2 select X from Y where Z IN ('$x')

Regards

Thanks for the reply.

Will the above cater for an infinate amount of values that could be stored in the parameter?

Cheers

if you have more than two values...

Param1Values="AAAA,BBBB,CCC,DDD"
x=$(echo $Param1Values | awk -F, -v s=\' '{for(i=1;i<=NF;i++) {printf s $i s;printf (i==NF?_:",")}}' ) 
db2 select X from Y where Z IN ('$x')

Nealry there :smiley:

The above gives the result:

db2 select X from Y where Z IN (''AAAA''BBBB''CCC''DDD'')

How would i get the code to give the results in the format:

db2 select X from Y where Z IN ('AAAA','BBBB''CCC','DDD')

So that there is single quotes around each string, and comma seperated?

Thanks once again!

perl -e'
  printf "select X from Y where Z IN (%s)\n",
    join "," , map "\47$_\47", split ",", $ENV{Param1Values}
    '

You should export the Param1Values variable before executing the script:

export Param1Values

Thanks for the reply, much appreciated, but i am trying to stay away from perl and use AWK or SED if possible.

Cheers

Fixed here...

Param1Values="AAAA,BBBB,CCC,DDD"
x=$(echo $Param1Values | awk -F, -v s=\' '{for(i=1;i<=NF;i++) {printf s $i s;printf (i==NF?_:",")}}' ) 
db2 select X from Y where Z IN ('$x')

Why?

x=$(echo $Param1Values | awk -F, '{$1=$1;print "\047" $0 "\047"}' OFS="\047,\047")

Thats worked the treat! :smiley: :smiley: :smiley:

Thanks alot!

With zsh:

% print $Param1Values        
AAAA,BBBB,CCC,DDD
% print ${(j:,:)${(qqs:,:)Param1Values}}
'AAAA','BBBB','CCC','DDD'

You can try also Franklin method...

x=$(echo $Param1Values | awk -F, '{$1=$1;print "\047" $0 "\047"}' OFS="\047,\047")
sed "s/,$/,,/; s/\([^,]*\)/'\1'/g; s/,$//"