Recursively chown all files that are owned by a specific user

Is it possible to find and chown all files that a specific user owns? I did a bunch of things as the wrong user and need to give the correct user ownership of the files.

Is there a recursive and conditional way I can chown a bunch of files and directories?


Solution 1:

You can use this portable find command with something like this.

find . -user old-user -exec chown new-user:new-group {} \;

You can expand this to find specific files with -iname options (non POSIX but available on OSX)

find . -iname '*.html' -user www-data -exec chown www-data:www-data {} \;

The . stands for the current folder and below, so you could use a specific path as a base.

find /var/www/ -iname '*.html' -user www-data -exec chown www-data:www-data {} \;

Solution 2:

You can use

chown --from=CURRENT_OWNER:CURRENT_GROUP -R new_owner:new_group  *

From the manual chown --help:

  --from=CURRENT_OWNER:CURRENT_GROUP
                     change the owner and/or group of each file only if
                     its current owner and/or group match those specified
                     here.  Either may be omitted, in which case a match
                     is not required for the omitted attribute.

edit: This, of course, only works on linux and most UNIces. For OSX (which is based on BSD) see the solution of @StephenTrapped.