Accessing newest file in a directory

Posted on April 18, 2021

There are many instances where I want to access the most recent file in a directory:

I recently discovered glob qualifiers, which is perfect for these tasks. In the shell * expands to all files and directories. Zsh has options to qualify which files needs to be expanded. In particular:

Thus, for my first two use cases, I can use:

z desired-directory && mv ~/Downloads/*(.om[1]) ./

For the third use case:

z luametatex && sudo pacman -U *(.om[1])

Sometimes, I want to use the latest file matching a particular pattern (say, the latest PDF file with pattern in the title). In such cases, I can use:

mv ~/Downloads/*pattern*.pdf(om[1]) ./

Or, if I want to see the name of the file before moving it:

mv ~/Downloads/*pattern*.pdf^Xm

(where ^Xm means press CTRL+X m). Search for _most_recent_file in zshcompsys for details.


This entry was posted in Terminal and tagged zsh, glob qualifiers, zshexpn.