Linux One Liner – Finding Stuff

Let’s say you created a file in your home directory but can’t work out which directory you put it in.

$ find ~ -name somefile.txt

You can replace ~ (tilda) with a directory e.g. / (slash) for search all locations on your system.

Let’s say you want to find all the JPEG’s you have.

$ find ~ -name "*.jpg"

Now to improve on this, I know I put a JPEG somewhere in the past few days, give me just the files from the past 3 days.

$ find . -name "*.jpg" -mtime -3

And what if you only wanted files greater then 2MB

$ find . -name "*.jpg" -mtime -3 -size +2M

If you want to look at a more detailed listing of the files found, like the format you are familar with using ls, try this.

$ find . -name "*.jpg" -mtime -3 -exec ls -l {} ;

You can find more then files, lets find all the directories you have.

$ find ~ -type d

I haven’t added it, but historically you needed to add -print on the end to print the results, seems nowadays this is optional.

I briefly used the -exec option above, I used it for various purposes. Here are a few.

$ find /backup-location -name "backup.*.tar.gz" -mtime +3 -print -exec rm -f {} ;
$ find . -name CVS -exec rm -rf {} ;

The first I run against my backup directory, that removes the online backups older then 3 days. Of course I’ve also got offline backups.
The second is when I checkout stuff from CVS and I want to prune all the CVS information. NOTE: Using the rm -rf command is very dangerous, you should only use this when you know your stuff. Used in the wrong way you delete everything, if you don’t have backups, there ain’t any UNDO in Linux. Also if you do it as root, you can effectively kill your installation in a split second.

There are other commands that perform various level of finding (e.g. commands via path) and other various stuff. A topic for another time, but to entice you.

$ which find
$ whereis find
$ locate find


  1. Dan says

    The gnu find also has a -ls option that will print the results in a format similar to “ls -l”. No need to use -exec, which can be much slower since it spawns one process for each file found. For example:
    find . -name “*.jpg” -mtime -3 -ls

    Along the same line, if you want to run a command that takes the file names as the last parameter (in other words, you can’t specify the where to put the result via {} ) use -print0 (that’s a zero) and pipe the output to “xargs -0″ like this:
    find . -name “*.jpg” -mtime -3 -print0 | xargs -0 ls -li
    Using xargs will cause it to only spawn as many processes as necessary to fit them on as few command lines as possible. Unless your find results in hundreds or thousands of results, this will usually be just one spawned process, making everything quicker.