bashshellunixlocate

Is there a way to use the Locate database to perform a copy in Unix Shell?


From a Unix shell.

I want to find a file specifically using locate <filename> and then I want to copy the files that were located using cp. I've tried something like:

Locate -name "*.doc" -exec cp {} /path/to/copy/to


Solution

  • If you want to perform actions with files-path found by the locate database, the locate command has no -exec option to execute a command on located files (-exec exist for the find command).

    If working with the Locate database's locate command:

    1. You probably want to locate from the base name rather than the whole path; so use -b '*.doc'.
    2. You want the pattern inside single quotes so it is not expanded by the current shell interpreter, but only by the locate command.
    3. You want the located files to actually exist so use the -e switch.
    4. You want a null delimited list of entries, so it is safe to iterate paths, even if it contains non-printable special characters, spaces, newlines, tabs…
    5. Since locate has no direct mean to execute a command with arguments, you will pipe the output stream into xargs to do it instead.
    locate -0eb '*.doc' |
      xargs -0 \
        sh -c 'cp -- "$@" /path/to/copy/to/' _
    

    Explanations:

    Finally note some key differences between locate and find:

    For further reading, see: SuperUser.com: What is the difference between 'locate' and 'find' in Linux?