There are several approaches. The simplest is to change into the first directory
cd dir1 ; cp $files ../dir2
One problem is that a string with names separated by spaces is not the best form for manipulating the names, in particular if they contain spaces. What you have is what you have, but let us hope you have bash, zsh, ksh or something like it which has arrays. Change the string into an array:
names=( $files )
Then you can apply transformations such as prepending "dir1/" onto each element of the names array.
cp "${names[@]/#/dir1/}" dir2
This is not the most obvious syntax, so let me break it down a bit.
- The first
/
introduces a substitution operation.
- The
#
matches the start of the element, similar to ^
in regular expressions.
- The second
/
ends the "from" part of the substitution.
- The
dir1/
is the "to" part of the substitution, there is nothing special about the third /
it is just a character in the "to" part.
- The
[@]
makes it apply to all elements in the array. The use of [@]
inside double quotes stops word splitting.
- The
{
and }
are needed to group the [@]
and the substitution operation together with the variable name.
- The
$
is just the normal variable reference.