user3920295
user3920295

Reputation: 909

copy only the files in a directory

I have 2 directories

       dir1/results1/a.xml
       dir1/results1/b.txt

and

      dir2/results2/c.xml
      dir2/results2/d.txt

I want to copy only the files in dir2/results2 folder into dir1/results1 folder so that the result is like this:

         dir1/results1/a.xml
         dir1/results1/b.txt
         dir1/results1/c.xml
         dir1/results1/d.txt

I tried shell comand

         cp -R dir2/results2/ dir1/results1/

but it is getting copied as

          dir1/results1/a.xml
          dir1/results1/b.txt
          dir1/results1/results2

what is the right way to do it?

Upvotes: 1

Views: 86

Answers (3)

Joshua
Joshua

Reputation: 43268

(cd dir1 && find . -maxdepth 1 -type f -print0 | tar -T - --null -cf - ) | (cd dir2 && tar -xf -)

Handles all cases including . files and very large files but won't copy sibdirs. Remove the -depth to copy sibdirs. Requires gnutar.

Upvotes: 0

user1934428
user1934428

Reputation: 22225

In your concrete case,

cp dir/results2/* dir/results1

would do what you want. It would not work well in two cases:

  • If you have files starting with a period, for instance dir/results2/.abc. These files would not be copied.

  • If you have subdirectories in dir/results2. While they indeed would not be copied (as you required, because you want to copy only files, not directories), you would get an error message, which is at least not elegant.

There are solutions to both problems, so if this is an issue for you, create a separate post with the respective topic.

(UPDATE) If the filename expansion would generate an argument line which is longer as the allowed minimum (for instance, if there are many files in the directory, or those with long lines), my solution would not work either. In this case, something like

find dir/results2 -maxdepth 1  -type f | xargs -i --no-run-if-empty] cp {} dir/results1

This would also solve the problems with the hidden files, which I have mentioned above.

Upvotes: 2

Jay jargot
Jay jargot

Reputation: 2868

tarcommand is very handy for that.

Give this a try:

tar cf - -C dir2/results2 . | ( cd dir1/results1 ; tar xf - )

It will not only copy plain files but also any other ones found into dir2/results2, such as directories etc.

Upvotes: -1

Related Questions