1

I want to exclude two directories while copying.

Example:

$ ls /root/tmp
a b c d e f    

I want to exclude directories a and b:

$ cp -rp /root/tmp/ /root/tmp1/
denis
  • 21,378
  • 10
  • 65
  • 88
Mouna Vignesh
  • 13
  • 1
  • 1
  • 9
  • Hope [this](https://stackoverflow.com/questions/4585929/how-to-use-cp-command-to-exclude-a-specific-directory) already has an answer – Nerdy Sep 20 '17 at 10:48
  • In this commad only one folder has excluded. I want to exclude two directory's in one command – Mouna Vignesh Sep 20 '17 at 10:52
  • try: `ls | grep -Pv '^(a|b)$' | xargs -I xxx echo xxx` in place of `echo` use your `cp` command – Shakiba Moshiri Sep 20 '17 at 11:54
  • Does this answer your question? [How to use 'cp' command to exclude a specific directory?](https://stackoverflow.com/questions/4585929/how-to-use-cp-command-to-exclude-a-specific-directory) – cdeszaq Jul 22 '22 at 18:11

4 Answers4

6

rsync can be used to exclude multiple directories like this:

rsync -av --exclude=/root/tmp/a --exclude=/root/tmp/b /root/tmp/ /root/tmp1/

with cp command

cp -r /root/tmp/!(a | b) /root/tmp1/

Execute shopt -s extglob before cp command to enable ! in cp

Nerdy
  • 1,016
  • 2
  • 11
  • 27
2

Try the below rsync it works for me on ubuntu 14.04

rsync -av --exclude='/root/tmp/a' --exclude='/root/tmp/b' 
/path/to/include /path/to/include /path/to/destination
justaguy
  • 2,908
  • 4
  • 17
  • 36
2

You could exclude the directories as part of find results before the copy, but using rsync or cp with the '!' support enabled as suggested by Sathiya is a much simpler solution.

See find example below:

find /root/tmp/ -mindepth 1 -maxdepth 1 -type d ! -regex '\(.*a\|.*b\)' -exec cp -r {} /root/tmp1/ \;
Shakiba Moshiri
  • 21,040
  • 2
  • 34
  • 44
0

You can do this in bash (does not work in sh):

shopt -s extglob
cp -r !(somefile|somefile2|somefolder) destfolder/
t7e
  • 322
  • 1
  • 3
  • 9