0

i have two sets of data, say a=file1 file2 file3 and b=location1 location2 location3. Now i need to loop through and copy file1 to location1, file2 to location2 and file3 to location3.

If I use for loop, then after the first iteration of the the inner loop, it should go back to the outer loop, take the second value, go to the inner loop and take the second value and so on. Basically, the inner loop should not iterate for every value in the outer loop.

Is there a way to do this?

Thanks in advance. Sudhir

2
  • where are the lists of files coming from? Are you walking a directory or a folder? Commented Jul 9, 2013 at 19:14
  • which shell (and what version) are you using? Commented Jul 9, 2013 at 19:18

3 Answers 3

1

It sounds like you're getting too complicated:

a=(file1 file2 file3)
b=(location1 location2 location3)

for (( idx=0; idx<${#a[@]}; idx++ )); do
    cp -v "${a[idx]}" "${b[idx]}"
done
Sign up to request clarification or add additional context in comments.

1 Comment

this worked like a charm. thanks a ton for your time. i cant use perl as this is a part of a bigger script. thanks to all
1

You can create bash arrays and make it work for you:

declare -a f=( "file1" "file2" "file3" )
declare -a d=( "location1" "location2" "location3" )
c=0
for i in ${f[@]}; do
   echo $i ${d[$c]}
   ((c++))
done

Or without arrays something like this script should also work for you:

ci=0
for i in file1 file2 file3; do 
   ((ci++))
   cj=1
   for j in location1 location2 location3; do
      [[ $ci = $cj ]] && echo $i $j && break
     ((cj++))
   done
done

OUTPUT:

file1 location1
file2 location2
file3 location3

Comments

1

For sure $SHELL is simplest here, although once you start doing arrays with bash that advantage starts to dissipate ;-) So, just for comparison, here is a simple, non-oneliner perl approach:

 #!/usr/bin/env perl
 my @arraya = qw/ file1 file2 file3/ ; 
 my @arrayb = qw/ location1 location2 location3/ ;
 foreach my $i ( 0 .. $#arraya ) {`cp $arraya[$i] $arrayb[$i]` }

@arraya and @arrayb can be constructed programmatically into very large lists with /m// matching and filtering, greping, finding, etc.

c.f. the perl based rename tool.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.