1

I have a file called "foo.txt" in my current directory. This directory also has folders named myfolder1, myfolder2, etc... Each of these folders has a subfolder called "constant".

I want to copy "foo.txt" into myfolder1/constant, myfolder2/constant, etc...

I tried to do this with the command:

cp foo.txt myfolder*/constant

This resulted in the error:

cp: omitting directory `myfolder1/constant'
cp: omitting directory `myfolder2/constant'
etc...

Is there a way I can copy a file into the sub-folder of multiple directories with the same prefix (in this case, the prefix being 'myfolder')?

1

When cp gets more than two arguments, the last one is taken as the destination directory and the other ones the files to copy there.

cp doesn't know that you used a wildcard: wildcards are expanded by the shell before the command sees them. So even if cp had some kind of multi-target capability, it couldn't use this syntax.

You'd need a loop. In Bourne-like shells:

(ret=0
for dir in myfolder*/constant/; do
  cp foo.txt "$dir" || ret=$?
done
exit "$ret")

The $ret business is to report any cp failure in the exit status in the end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.