os2mac
April 8, 2013, 4:36pm
1
So I have several files:
1.txt 2.txt 3.txt 4.txt
and several directories:
one two three four
I want to put one file in one directory, thusly:
1.txt to /one
2.txt to /two
3.txt to /three
4.txt to /four
but I want to use a for loop to do something like this:
!#/usr/bin/bash
file=(1.txt 2.txt 3.txt 4.txt)
dir=(one two three four)
for i in ${file[@]};do
cp $i ${dir[@]}
done
This will obviously attempt to put EVERY file in EVERY directory. How would I limit it as stated above?
Thanks,
Yoda
April 8, 2013, 5:05pm
2
You could do something like below using a counter:
file=( 1.txt 2.txt 3.txt 4.txt )
dir=( one two three four )
c=0
for i in ${file[@]};
do
cp $i ${dir[$c]}
(( ++c ))
done
1 Like
os2mac
April 8, 2013, 5:13pm
3
I always for get to include the environment...
Yoda
April 8, 2013, 5:16pm
4
It should work in Solaris. I tested using GNU bash, version 3.2.51(1)-release (sparc-sun-solaris2.10)
and it works.
1 Like
RudiC
April 9, 2013, 5:55pm
6
Why not
$ file=(1.txt 2.txt 3.txt 4.txt)
$ dir=(one two three four)
$ echo ${#dir
[*]}
4
$ for ((i=0; i<${#file[@]}; i++)); do echo cp ${file} ${dir}; done
cp 1.txt one
cp 2.txt two
cp 3.txt three
cp 4.txt four