Useful Linux Command: Find File By Name, Sort By Date

Tue, 25 Jan 2022, by Syrsly

The command below finds a file based on its filename and then sorts the results by oldest to newest:

find . -type f -name "*string you are looking for in filename*" -printf "%T@ %Tc %p\n" | sort -n

So yeah, this may seem like black magic or a dangerous command, so let me explain what each piece does. First, the "find" command is what it sounds like, a search tool. It finds things. The first parameter, ".", is just a filepath to tell it to search in. This could easily be replaced with whatever other path you want to look in. If you leave it as a dot, this means to search in the directory you're currently in.

Next, you have the "-type f" parameter. This tells find to find files of a specific type. When you say "-type f", you're saying only to return files rather than also returning directories, links, etc. This parameter is optional, but it can make a huge difference in some use cases. I personally like to omit this parameter most of the time because I like to search for file links a lot and could easily forget I was using this parameter when looking at empty results.

The "-name" parameter is a little more obvious: it's the name string you're searching for. This can use some simple regex, though all you really need is the asterisk on either side to control the "starts with", "ends with" or "contains" state. If you have an asterisk on both sides, it's the "contains" state, meaning it will return any file with the string in its name.

The "-printf" parameter is mostly for presentation, but the options we fed it display like so: %T@ (timestamp) %Tc (day and date) %p (file path/name) \n (newline)

Finally, we use a pipe character to literally pipe these results into the sort function to sort them from oldest to newest using "-n".