1837097 Members
2261 Online
110112 Solutions
New Discussion

Creating a script

 
SOLVED
Go to solution
Michael Allmer
Frequent Advisor

Creating a script

I would like some help with a script that I am attempting to write. My goal is to move data from one location and place it in another. I have a list of data in one file (file1) and a list of new locations in another file (file2). The files hare identical except for the beginning part of the path in each line. This is what I see as the end command.
for each item
cp -r (item in file1) (item in file2)
5 REPLIES 5
Jordan Bean
Honored Contributor

Re: Creating a script


It would be convenient to have both files merged into one, named file, such that each line has two items delimited by whitespace. The first example covers this approach:

#!/usr/bin/sh
while read item1 item2
do
cp -pr $item1 $item2
done < file

To use separate files of identical length and order, this should work:

#!/usr/bin/sh
exec 3< file1
exec 4< file2
while read -u3 item1
do
if read -u4 item2
then
cp -pr $item1 $item2
fi
done
exec 3<&-
exec 4<&-

More can be done to test for the existence of the source files/directories and the ability to create the target locations.
Jean-Luc Oudart
Honored Contributor

Re: Creating a script

Mike,

assuming filenames are unique in each file :
you could run a script like :
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#!/bin/sh
for filename in `cat file1`
do
echo $filename
f1=`basename $filename`
f2=`grep $f1 file2`
cmd="cp $filename $f2"
echo $cmd
done
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This also assume all the file names exist.
in file1 is a list of pathnames
in file2 is a list of target pathnames

instead of echo $cmd use eval $cmd.

Try it in your test environment 1st.
Hope this help

Jean-Luc
fiat lux
Rodney Hills
Honored Contributor
Solution

Re: Creating a script

This might work, but I would test it first...

paste file1 file2 | xargs -n2 cp -r

If file1 is
aaa
bbb

and file2 is
ccc
ddd

then the result is-
aaaccc
bbbddd

is pipe to xargs, which will then generate-
cp -r aaa ccc
cp -r bbb ddd

Hope this helps...

-- Rod Hills
There be dragons...
Michael Allmer
Frequent Advisor

Re: Creating a script

I want to thank all of you for your assistance with this issue. I have a workable solution to my problem now.

Jordan Bean
Honored Contributor

Re: Creating a script

Thank you, Rodney! I knew there was a command to merge two files like that, but I couldn't think of it. Paste. Almost doesn't make sense.