January 08, 2009 Archives

08-01-2009 18:26

Copy all files and folders but exclude some.

The cp command, in my opinion, should have an exclude switch available to it. I find myself needing to copy everything but a file or a folder and cp can't handle this requirement. So with a bit of googling around and testing, I have a way to do it. To copy all in the current folder to "bar/" excluding any folder or file called "foo", we do this:

for i in * ; do if [ "${i}" != "foo" ] ; then cp -r "${i}" "bar" ; if ; done

If you need to exclude a few files and folders, simply add in an AND operand and the value, like so:

for i in * ; do if [ "${i}" != "foo" ] && [ "${i}" != "example.txt" ]; then cp -r "${i}" "bar" ; if ; done

I didn't error check that, just did it from memory, so I hope it works for you.


Posted by DaveQB | Permanent Link | Categories: IT