6

How do you exclude a folder when performing file operations i.e. cp etc.

I would currently use the wild card * to apply file operation to all, but I need to exclude one single folder.

The command I'm actually wanting to use is chown to change the owner of all the files in a directory but I need to exclude one sub directory.

Camsoft
  • 961
  • 4
  • 12
  • 21
  • Cross-posted here: http://stackoverflow.com/questions/2065447/how-do-i-exclude-a-folder-when-performing-file-operations-i-e-cp-mv-rm-and-cho – Dennis Williamson Jan 14 '10 at 16:27

3 Answers3

7

Inverse Globbing:
You want an inverse match of a glob, I would do it like the following:

You can do an inverse match with a newer bash if you enable extended globbing. For example, to match everything that doesn't have foo or bar in the name:

shopt -s extglob
echo !(*foo*|*bar*)

Or just everything that doesn't have foo:

shopt -s extglob
echo !(*foo*)

Find:
You could also use find (this is the most robust option I think), and use ! to negate a match, and then run the command with xargs -0:

find . ! -iname 'foo' -print0 | xargs -0 echo

Simple:
Just mv the folder somewhere else, do what you need to do, and put it back :-)

Kyle Brandt
  • 83,619
  • 74
  • 305
  • 448
1

rsync -arv --exclude={files} {Destination}

Tman
  • 111
  • 7
-1

the find solution spawns one chown process per file, sometimes that can be a problem. This solution spawns only one perl process:

find . | perl -nle "chown($(id -u user), $(id -g group), \$_) unless m/foo/"
  • No, the `find` solution doesn't do this if you use it with `xargs`. Your script would also not only exclude the directory `/foo`, but also the file `/bar/foo` and the directory `/foobar`. – Sven Dec 16 '14 at 03:44
  • Yes, you have to adjust the regular expression as needed. Might I also point out that glob based solutions will also have the problem of matching /foobar – Antonio Dolcetta Feb 16 '15 at 08:17