I have similar file sturecture:


I want to copy from this directory only folders named static. These folders can be also subfolders. And it should form the same structure in new folder it had before. I.e.:

cp -r /home/* /otherhome/

I've tried this:

find home/ -name 'static' -exec cp -r '{}/*' 'otherhome/{}' ';'

But I get errors that /home/dave/documents/static/* and other static folders don't exist. I guess I can't concat the filenames with /*. Any idea how to do it?

  • So you want to recursively copy the contents of each static folder to otherhome?
    – slhck
    Nov 18, 2013 at 17:45
  • Yes, so after the operation I would be left with e.g. /otherhome/dave/documents/static/ and other static folders and nothing else.
    – davekr
    Nov 18, 2013 at 17:50

1 Answer 1


The problem is that those directories do not exist when you try to copy them over. You'd have to make them first.

find home -type d -name 'static' -print0 | while IFS= read -rd '' dir; do 
    mkdir -p otherhome/"$newdir"   
    cp -R "$dir" otherhome/"${newdir%static}"

We need to strip the home/ from the original directory names and then create the new folder hierarchy (mkdir -p). Then we copy over the contents recursively, but we also need to strip static from the end of the new directory so as not to create static/static.

There might be a prettier way to achieve this.

Example before and after:

├── home
│   ├── dave
│   │   ├── documents
│   │   │   └── static
│   │   │       └── Untitled.txt
│   │   ├── otherfolders
│   │   └── pictures
│   │       └── static
│   │           └── Untitled2.txt
│   └── static
└── otherhome
    ├── dave
    │   ├── documents
    │   │   └── static
    │   │       └── Untitled.txt
    │   └── pictures
    │       └── static
    │           └── Untitled2.txt
    └── static

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.