In a recent Opensource.com article, Lewis Cowles introduced the find command.
Find is one of the most powerful and flexible command-line programs in the daily toolbox, so it’s worth spending a little more time on.
At the very least, finding takes a path to finding things. For example:
/find (and print) every file on the system. And since everything is a file, you will get a lot of results to sort. This probably doesn’t help you find what you’re looking for. You can change the path argument to narrow things down a bit, but it’s still not really more useful than using the ls command. So you have to think about what you’re trying to locate.
You may want to find all JPEG files in your home directory. The -name argument allows you to restrict the results to files that match the given pattern.
find ~ -name ‘*jpg’
But wait! What if some of them have an uppercase extension? -iname is like -name, but is not case sensitive. find ~ -iname
Great! But the 8.3 naming scheme is so 1985. Some of the images may have a .jpeg extension. Fortunately, we can combine patterns with an “o,” represented by -o.
find ~ ( -iname ‘jpeg’ -o -iname ‘jpg’ )
We are getting closer. But what if you have some directories that end in jpg? (Why you named a bucketofjpg directory instead of images is beyond me.) We can modify our command with the -type argument to search only for files.
find ~ \( -iname ‘*jpeg’ -o -iname ‘*jpg’ \) -type f Or maybe you’d like to find
those strangely named directories so you can rename them later:
find ~ \( -iname ‘*jpeg’ -o -iname ‘*jpg’ \) -type d
It turns out you’ve been taking a lot of photos lately, so let’s narrow this down to files that have changed in the last week.
find ~ \( -iname ‘*jpeg’ -o -iname ‘*jpg’ \) -type f -mtime -7
You can perform time filters based on file state change time (ctime), modification time (mtime), or access time (atime). These are in days, so if you want finer grain control, you can express it in minutes (cmin, mmin, and amin, respectively). Unless you know exactly the time you want, you’ll probably prepend the number with + (more than) or – (less than).
But maybe you don’t care about your photos. Maybe you’ are running out of disk space, so you want to find all the gigantic files (let’s define that as “greater than 1 gigabyte”)
in the log directory: find /var/log -size +1G
Or maybe you want to find all the files owned
by bcotton in /data: find /data -owner bcotton
You can also search for permission-based files. You may want to find all the worldwide readable files in your home directory to make sure you’re not sharing too much.
find ~ -perm -o=r
This post only scratches the surface of what find can do. Combining tests with Boolean logic can give you incredible flexibility to find exactly the files you’re looking for. And with arguments like -exec or -delete, you can make it find taking action on what… Find. Do you have a favorite search expression? Share them in the comments!