dr0zd
dr0zd

Reputation: 1378

cp dir recursivly excluding 2 subdirs

I have 1 directory with 9 subdirectories and 10 files. Subdirectory have next level subdirectories and files.

/home/directory/
/home/directory/subdirectory1
/home/directory/subdirectory2
...
/home/directory/subdirectory9
/home/directory/file1
...
/home/directory/file10

I want to copy all subdirectories and files recursivly excluding:

/home/directory/subdirectory5
/home/directory/subdirectory7

What is the best way for it?

Upvotes: 10

Views: 24074

Answers (7)

Morten Pedersen
Morten Pedersen

Reputation: 29

Why not just use the cp command like this:

cp -r /home/directory/!(subdirectory5|subdirectory7) /destination

Upvotes: 1

kjohri
kjohri

Reputation: 1224

rsync -avz --exclude subdirectory5 --exclude subdirectory7 /home/directory/ target-path

Upvotes: 30

jfg956
jfg956

Reputation: 16750

You can use the --exclude option of tar:

{ cd /home/directory; tar -c --exclude=subdirectory5 --exclude=subdirectory7 .; } | { cd _destination_ ; tar -x; }

Upvotes: 2

Qian
Qian

Reputation: 1027

use rsync with --exclude is better

Upvotes: 2

kev
kev

Reputation: 161704

Maybe the find command will help you:

$ find /home/directory -mindepth 1 -maxdepth 1 -name 'subdirectory[57]' -or -exec cp -r {} /path/to/dir \;

Upvotes: 8

jon
jon

Reputation: 6246

Kev's way is better, but this would also work:

find "/home/folder" -maxdepth 1 | sed -e "/^\/home\/folder$/d" -e "/^\/home\/folder\/subfolder5$/d" -e "/^\/home\/folder\/subfolder7$/d" -e "s/^/cp \-r /" -e  "s/$/ \/home\/target/" | cat

Explained :

find "/home/folder" -maxdepth 1 |
// get all files and dirs under /home/folder, pipe output

sed -e "/^\/home\/folder$/d" 
// have sed strip the path being searched, or the cp -r we prepend later will pickup the excluded dirs again.

-e "/^\/home\/folder\/subfolder5$/d"
// have sed strip subfolder5

-e "/^\/home\/folder\/subfolder7$/d"
// have sed strip subfolder7

-e "s/^/cp \-r /"
// have sed prepend "cp -r " to each line

-e  "s/$/ \/home\/target/" | cat
// have sed append targetdir to each line.

Outputs:

cp -r /home/folder/subfolder9 /home/target
cp -r /home/folder/subfolder1 /home/target
cp -r /home/folder/file10 /home/target
cp -r /home/folder/subfolder2 /home/target
cp -r /home/folder/file1 /home/target
cp -r /home/folder/subfolder3 /home/target

Change | cat to | sh to execute the command.

<A big disclaimer goes here>

You should Kev's solution is better

Upvotes: 1

aioobe
aioobe

Reputation: 421030

I don't know a good way of doing it with cp, but it's fairly easy using rsync and the --exclude switch.

Upvotes: 11

Related Questions