18.9 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/ \;

The curly brackets are replaced by the filename and the escaped semicolon terminates the command string that belongs to the -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'


Your donation will support ongoing availability and give you access to the PDF version of this book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984. Copyright © 1995-2022 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0