I'm trying to write a script to copy files recursively from a particular folder except files A.extn, B/*.extn and C/* where B and C are directories and extn is just some generic extension. This is what I have:

However this doesn't do the negation of the pattern as expected. I think I do know why — although the pattern is correct (as seen with echo), cp -R is not aware of the pattern, and enters a directory that it is "not supposed to", and once in there, the pattern is no longer valid.

How do I modify the above to do what I want? I guess it is possible with find and xargs, but I'm drawn towards the clarity of the above and would prefer something similar (but if it's the wrong way to do it, I'd be perfectly happy with a different solution).

2 Answers
2

You are correct that the pattern is expanded before cp is run, so is unknown to that command.

You may be able to accomplish what you want by using the --parents option to cp rather than -R. That will only copy the files which match your pattern, but will use the full path name as supplied rather than only the trailing file name.

But, this option isn't portable. AFAIK, it's only supported by the GNU version of cp.

Your pattern may exclude the files you don't want to copy, but it doesn't exclude the directories containing them, and you told cp to copy recursively. So the files are copied anyway. Worse than that, if you have a source tree like

foo
foo/bar.txt
hello
hello/world
hello/world/wibble.txt

then the pattern expands to foo hello hello/world hello/world/wibble.txt so you end up with these files in $TMPDIR: