I want to copy an entire file structure (with thousands of files and hundreds of directories), it's a hierarchy of directories and there are those node_modules directory that I want to exclude from the copying process.

Is there a Unix command to copy from a directory and all of its files and sub-directories recursively with an option to say don't include the directories with the name <name> ?

Something like :

cp root/ rootCopy/ --except node_modules


If not, is there a simple way to do that from the command line without writing a bash or something ?


You can try with rsync or tar command .

See this or this post.

From rsync man page

    --exclude=PATTERN       exclude files matching PATTERN
    --exclude-from=FILE     read exclude patterns from FILE

rsync -avz --exclude 'dir*' source/ destination/
|improve this answer|||||
  • I managed to transfer my workspace lightweighted thanks ! – vdegenne Dec 30 '16 at 11:07

Creepy method, but it works for me:

(find source|egrep -v "node_modules|^source/exact/node_plugin" && echo tmptarget)|xargs cp --parents
mv tmptarget/source target

Explanation if needed. cp works like this:

cp source1 source2 ... sourceN target
  • So do the find to print your whole structure.
  • Use egrep to exclude all unwanted branches. Make sure you have properly formed your pattern. Use ^ and full path if you would like to exclude exact branch, or just node_modules if you want to exclude all of them.
  • printout the destination folder with echo command.
  • Let xargs put all these lines to cp command for you
  • --parents is needed to create parents folders, because we cant use -r option here, as it will mess everything on the target folder.
  • And finally mv whole new structure to real target
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.