Greg Rov Greg Rov - 11 months ago 36
Linux Question

Looping for two different variables at a time, Linux, unix

I need a command that uses looping to use two different variables at time.

Following this logic: (this command does not work, it is only an example):

for t1&t2 in 62&64 64&68 70&80; do

echo "Horse $t1 and $t2" >> File.out


and the final result would be


Horse 62 and 64
Horse 64 and 68
Horse 70 and 80

I want to use it, more specifically, with the R program like this way:

for t1&t2 in 62&64 64&68 70&80; do

R -q -e "library(pastecs);d <- read.table('ageecent.txt', header = F,sep=' ');
vart1 =var(d[,$t1]); vres_t1=vart1*0.75;
va_t1=(vart1*0.25);vart2=var(d[,$t2]); vres_t2=vart2*0.75;
va_t2=(vart2*0.25); cor=cor(d[,$t1],d[,$t2]);
write.table(va_t1,'va_t1', row.names=F, col.names=F);


Where will I need to use two different variables at a time, t1 and t2, that define the columns of my main file "ageecent.txt", that must be analyzed.
Thank you for your attention and support.

Answer Source

I would use a while loop in conjunction with read instead of a for loop:

echo -e '62 64\n64 68\n70 80' |
    while read -r t1 t2; do
        echo "Horse $t1 and $t2"
    done >> File.out

Note that I also moved the redirection out of the loop, it is more efficient this way.