106

I have two directories and one is empty.

The first directory has many sub directories with hidden files. When I cp -r content from first directory to the second one, the hidden files gets copied too. Any solutions to escape them?

dlmeetei
  • 9,905
  • 3
  • 31
  • 38
Rahul
  • 5,493
  • 6
  • 18
  • 12

4 Answers4

150

You can use rsync instead of cp:

rsync -av --exclude=".*" src dest

This excludes hidden files and directories. If you only want to exclude hidden directories, add a slash to the pattern:

rsync -av --exclude=".*/" src dest
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
42

You can do

cp -r SRC_DIR/* DEST_DIR

to exclude all .files and .dirs in the SRC_DIR level, but still it would copy any hidden files in the next level of sub-directories.

Tuxdude
  • 47,485
  • 15
  • 109
  • 110
5

rsync has "-C" option

http://rsync.samba.org/ftp/rsync/rsync.html

Example:

rsync -vazC  dir1 dir2
Tamil Selvan C
  • 19,913
  • 12
  • 49
  • 70
slitvinov
  • 5,693
  • 20
  • 31
  • You are right. I tried **mkdir -p dir1/subdir; touch dir1/subdir/.cvs; rsync -avzC dir1 dir2** – slitvinov Jul 19 '12 at 09:42
  • 1
    rsync -av --exclude=".*" src dest works great. Refer the answer above by eugene. Thanks anyway! :) – Rahul Jul 19 '12 at 11:07
1

I came across the same need when I wanted to copy the files contained in a git repo, but excluding the .git folder, while using git bash.

If you don't have access to rsync, you can replicate the behavior of --exclude=".*" by using the find command along with xargs:

find ./src_dir -type f -not -path '*/.*' | xargs cp --parents -t ./dest_dir

To give more details:

  • find ./src_dir -type f -not -path '*/.*' will find all files in src_dir excluding the ones where the path contain a . at the beginning of a file or folder.
  • xargs cp --parents -t ./dest_dir will copy the files found to dest_dir, recreating the folder hierarchy thanks to the --parents argument.

Note: This will not copy empty folders. And will effectively exclude all hidden files and folders from being copied.

Link to relevant doc:

https://linux.die.net/man/1/cp

https://linux.die.net/man/1/find

SivolcC
  • 3,258
  • 2
  • 14
  • 32