Link to home
Start Free TrialLog in
Avatar of Sharath S
Sharath SFlag for United States of America

asked on

bash string manipulation

I have a variable with value as
var="a,b,c"
I would like to convert that as in a bash script.
var="t1.a=t2.a AND t1.a=t2.b AND t1.c=t2.c"

I tried to split the string into an array iterate through the elements but could not able to generate the desired string.

Can anyone please help.

Thanks
Sharath
Avatar of YZlat
YZlat
Flag of United States of America image

give this a shot:

 
var="a,b,c"
arr=$(echo $var | tr "," "\n")
output=""

i=0
for x in $arr
do
    echo "> [$x]"
   if [ "$i" -eq 0 ]
   then
       output="t1."${x}"=t2."${x}" AND t1."${x}"=t2."
   elif [ "$i" -eq 1 ]
   then
       output=${output}${x}
   elif [ "$i" -eq 2 ]
   then
       output=${output}" AND t1."${x}"=t2."${x}

   fi
    i++
done

echo $output
 

Open in new window

Avatar of Sharath S

ASKER

YZlat, Thanks for your post.
your script only works for "a,b,c". What if I have a string like "a,b,c,d,e,f"?
However, I already wrote a script using for loop.
Is there any better way of doing this with sed/awk instead of loop?
Do you mean
var="t1.a=t2.a AND t1.b=t2.b AND t1.c=t2.c"
?
If not, what is the rule for producing
"t1.a=t2.a AND t1.a=t2.b AND t1.c=t2.c"  from "a,b,c"
and how would that rule apply to "a,b,c,d,e,f"?
yes. for each value in the string, change it to t1.str1=t2.str1
if var="a,b,c,d,e,f"
then var should be "t1.a=t2.a AND t1.b=t2.b AND t1.c=t2.c AND t1.d=t2.d AND t1.e=t2.e"
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ozo, simply superb. exactly what I am looking for.

Here is my effort on this. I am able to do this but not very straightforward.
I am still learning shell scripting and want to know if you can provide some pointers in learning sed/awk.  Thank you so much for your post.

var="a,b,c,d,e,f"
var=$(echo $var | tr ',' ' ')
var=($var)
for i in "${var[@]}"; 
do 
	var2=("${var2[@]}" "t1.$i=t2.$i") 
done
var=$(printf '%s,' "${var2[@]}")
var="${var:0:${#var}-1}"
var=${var//,/ AND }
echo $var

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I have used all those operations to achieve what I am looking for. I like your posts as you are simplifying all those operations. I am learning sed/awk, in fact the shell scripting.
There are lot of material available online. Will you be able to help me to start in right direction. Much appreciated.
man sed
and
man awk
are the primary online material I use.
Asking and answering questions here is a good excercise.
The O'Reilly lorises book is a good reference
Question 10 in the awk FAQ lists other resources
http://www.faqs.org/faqs/computer-lang/awk/faq/
Thanks ozo.