Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I'm currently trying to find (and copy) all files and folder structure matching a specific pattern, in a specified directory and I'm so nearly there!

Specifically, I want to recursively copy all folders not begining with a '_' character from a specified path.

find /source/path/with/directories -maxdepth 1 -type d ! -name _\* -exec cp -R {} /destination/path \;

In the /source/path/with/directories/ path are machine-specific directories beginning with '_' and others, and I'm only interested in copying the others. For a reason beyond me, the find command returns the /source/path/with/directories/ directory, and therefore copies its content, directories begining with '_' included.

Anyone have a hint as to why that is?

Thanks,

Pascal

share|improve this question

2 Answers 2

up vote 4 down vote accepted

find returns the root path because it matches your criteria—i.e. it is a directory, and it doesn't start with _.

You're looking for -mindepth 1, I suspect:

$ cd /tmp
$ mkdir a
$ touch a/b
$ mkdir a/c
$ touch a/c/d
$ find a
a
a/b
a/c
a/c/d
$ find a -mindepth 1
a/b
a/c
a/c/d

Reference: find manpage

share|improve this answer
    
Excellent! works as I wanted. I had it working by adding ! -name 'files' but it felt wrong to me... –  Pinpin Jun 20 '12 at 21:47

Change from:

find /source/path/with/directories ...

to:

(shopt -s dotglob; find /source/path/with/directories/* ... )

That way /source/path/with/directories will not be included.

The shopt -s dotglob is so that * will also match files and directories starting with a . (hidden files, directories).

And the whole thing is wrapped in a sub-shell with (...) to limit the effect of shopt only within the sub-shell, otherwise you would have to undo it later with shopt -u dotglob.

share|improve this answer
    
That will fail for directory entries that start with .. Don't try .*, either, or you'll match a whole lotta other stuff you never intended to. ;-) –  zigg Jun 20 '12 at 20:11
    
Good point, updated the answer, added using shopt. –  janos Feb 15 '13 at 7:48

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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