5

I have a directory which has a lot of header files(.h) and other .o and .c files and other files. This directory has many nested directories inside. I want to copy only header files to a separate directory preserving the same structure in the new directory.

cp -rf oldDirectory newDirectory will copy all files. I want to copy only header files.

taskinoor
  • 45,586
  • 12
  • 116
  • 142
avimonk
  • 173
  • 2
  • 11
  • Possible duplicate of [Recursive copy of specific files in Unix/Linux?](http://stackoverflow.com/questions/9622883/recursive-copy-of-specific-files-in-unix-linux) – iammilind May 09 '17 at 11:47

3 Answers3

8
(cd src && find . -name '*.h' -print | tar --create --files-from -) | (cd dst && tar xvfp -)

You can do something similar with cpio if you just want to hard link the files instead of copying them, but it's likely to require a little mv'ing afterward. If you have lots of data and don't mind (or need!) sharing, this can be much faster. It gets confused if dst needs to have a src in it - this is, if it isn't just a side effect:

  1. find src -name '*.h' -print | cpio -pdlv dst
  2. mv dst/src/* dst/.
  3. rmdir dst/src
taskinoor
  • 45,586
  • 12
  • 116
  • 142
user1277476
  • 2,871
  • 12
  • 10
2

this one worked for me:

rsync -avm --include='*.h' -f 'hide,! */' . /destination_dir

from here

Community
  • 1
  • 1
Ben
  • 3,832
  • 1
  • 29
  • 30
-1
cp -rf oldDirectory/*.h newDirectory

or something like (depending on the actual paths)

find oldDirectory -type f -name "*.h" -print0 | xargs -file cp file newDirectory
scibuff
  • 13,377
  • 2
  • 27
  • 30
  • 5
    First solution copies .h files at depth 1 only. What if we have header files at depth 2 and 3 and so on. – avimonk Apr 16 '12 at 16:20