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.

1

3 Answers 3

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 :-)

1

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

-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/"
2
  • 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, 2014 at 3: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 Feb 16, 2015 at 8:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .