I have a directory main_dir which contains lots of files and 3 subdirectories (dir1 and dir2 and dir3). I want to copy it to another location without copying dir2 in one command. I searched the cp manual to see if this can be done somehow but I did not find the answer.
My only solution was to copy the whole directory and then delete dir2 in the copied location.
cp -r main_dir ~/Documents/main_dir_copy
cd ~/Documents/main_dir_copy
rm -r dir2
Is there a way to do this without having to copy all the contents of dir2 and then delete it?
Best Answer
In bash, you can use an extended glob to implement negation.
Given
then
resulting in
Note that since this recursively copies the contents of
main_dir
(excluding the givendir2
) rather thanmain_dir
itself, the target directorymain_dir_copy
must already exist - if it doesn't, addmkdir main_dir_copy
to the command sequence.See also