GNU/Linux Desktop Survival Guide
by Graham Williams |
|||||
Find Files |
20190331 The find command is a powerful tool used to discover files that match a pattern and then to perform some action with that file. The default is simply to print the full path and name of the files found. Here we find files somewhere in the current directory and down the hierarchy with a name that finishes with .jpg:
$ find . -type f -name '*.jpg' ./Photos/misc/20210424.jpg ./Photos/misc/20321214.jpg ./Photos/profiles/20200720.jpg ./Photos/posts/20200618_2021.jpg ./Photos/posts/20200618_2022.jpg ./Photos/posts/20200618_2024.jpg |
A regular expression can also be used as here finding jpg filenames containing a sequence of 6 digits:
$ find . -type f -regextype sed -regex '.*[0-9]{6}\.jpg' ./Photos/misc/20210424.jpg ./Photos/misc/20321214.jpg ./Photos/profiles/20200720.jpg |
Or to find those files that do not match the pattern:
$ find . -type f -regextype sed -not -regex '.*[0-9]{6}\.jpg' ./Photos/posts/20200618_2021.jpg ./Photos/posts/20200618_2022.jpg ./Photos/posts/20200618_2024.jpg |
So far we have simply listed the files so found. We can perform some
other action on the files using -exec
:
find . -name '*.jpg' -exec mv {} /media/sabrina/photos/ \; |
-exec
.
Often we will be searching storage areas where we may not have permission to some parts of it. In this case it is useful to redirect the standard error output to the null device to avoid screens full of error messages, or run the command as the root user through sudo:
$ find / -name 'sources.apt' 2>/dev/null $ sudo find / -name 'sources.apt' |