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
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:
-b '*.doc'
.locate
command.-e
switch.null
delimited list of entries, so it is safe to iterate paths, even if it contains non-printable special characters, spaces, newlines, tabs…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:
locate -0eb '*.doc'
: Using the locate database; locate files that still exist right-now having the base name matching the *.doc
pattern, and output the list as a null
delimited list of paths.| xargs -0
: Pipe the null
delimited list of paths to xargs
to pass the entries as argument to the following command.sh -c
: Execute the inline shell script that follow.cp -- "$@" /path/to/copy/to/'
: The inline shell script that copy all received paths as arguments array $@
into /path/to/copy/to/
.Finally note some key differences between locate
and find
:
locate
uses a database to reference files within the system. There is a programmed cron
job, to update the Locate database (usually once a day, calling the /etc/cron.daily/mlocate
script for example). locate
is fast because of that, but it also cannot find recent files until it has updated its database.find
directly accesses the filesystem. It traverses directories recursively and identify files/paths endpoint types. It also has more options and capabilities like passing paths as arguments and execute commands.For further reading, see: SuperUser.com: What is the difference between 'locate' and 'find' in Linux?