LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   loops in scripts (https://www.linuxquestions.org/questions/linux-newbie-8/loops-in-scripts-4175414728/)

JM_T 07-03-2012 03:39 PM

loops in scripts
 
I am trying to batch process some files. So far I have used only single files, using

for i in ax bx cx dx nx etc...
do
command1 (e.g. /../test$i)
command2 (e.g. /../test$i)
done

I have files that need to be "coupled".
e.g. ax with dx, bx with cx, nx with nnx, ....

all this is in a fairly random order and I have a table/matrix with the filenames coupled. They have to be processed together before going to the next one, and I can't figure out how to do it.
e.g. commands will look like
command1 ../../test/ax/dx
command2 ../../test/ax/dx

where the loop then should jump to
command1 ../../test/bx/cx
command2 ../../test/bx/cx

etc.

THANKS!!!!

montel 07-03-2012 04:55 PM

I don't fully understand what you are trying to do, some more explanation would be very helpful.

JM_T 07-03-2012 05:07 PM

Basically I need to use 2 linked variables in one command line, repeat a few commands with this set of variables. Then next 2 variables need to go through the same set of commands are unrelated to the first 2, etc.
With "for i in..." I have been able to do this type of a loop with a single variable, but combining multiple sets of 2 linked variables within one loop I have not been able to figure out.

Hope that clarifies it better, not sure how better to put it. Thanks

suicidaleggroll 07-03-2012 05:14 PM

Like this?

Code:

#!/bin/bash

arr1=("ax" "bx" "nx")
arr2=("dx" "cx" "nnx")

for ((i=0; i<${#arr1[@]}; i++)); do
  echo command1 ../../test/${arr1[$i]}/${arr2[$i]}
  echo command2 ../../test/${arr1[$i]}/${arr2[$i]}
done

Output is
Code:

command1 ../../test/ax/dx
command2 ../../test/ax/dx
command1 ../../test/bx/cx
command2 ../../test/bx/cx
command1 ../../test/nx/nnx
command2 ../../test/nx/nnx


Just remove the echo from the lines to actually run the commands, rather than just printing out what it would run.

grail 07-03-2012 08:57 PM

Another take would be to use your file with the pairings in it. Assuming this looks like:
Code:

$ cat pairing_file
ax dx
bx cx
nx nnx

We can then read this in with a while loop like so:
Code:

while read -r first second
do
    command1 "../../test/$first/$second"
    command2 "../../test/$first/$second"
done<pairing_file


JM_T 07-04-2012 11:55 AM

Thank you so much, that worked perfectly.

grail 07-05-2012 12:30 AM

Please remember to mark as SOLVED once you have a solution.

kgntech 07-05-2012 01:41 AM

It was just amazing information sharing and it's helpful for everyone.


All times are GMT -5. The time now is 09:44 AM.