Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Simple requirement but can't find anything online which can achieve it.

I have a list of dated files as below...


I need a script which selects the most recent file based on the date in the filename (not the file's date stamp). There's loads of help about for selecting the most recent stamp date but not for selecting the greatest filename date.

share|improve this question
up vote 3 down vote accepted

ls(1) sorts files by name, so ls | tail -1 should do.

share|improve this answer
Or use -r for sorting in reverse order: ls -1r | head -1 – shantanoo Mar 5 '13 at 4:25

Obligatory zsh answer:

echo "The highest-numbered file is" filename_*.dat([-1])

This is a glob with the glob qualifier [NUM] to retain only the NUMth match (a negative value counts from the last match). If you have numbers of varying width, add the n qualifier to

% ls
filename_1.dat filename_12.dat filename_17.dat filename_2.dat filename_8.dat
% echo filename_*.dat([-1])
% echo filename_*.dat(n[-1])

Globbing only happens in a context that looks for a list of words, so if you want to assign the filename to a variable, you need to make it an array which will contain one element:

echo "The highest-numbered file is $latest"

In any shell, you can set the positional arguments to the full list of matches and keep the last one.

set_latest () {
  set -- filename_*.dat
  eval "latest=\${$#}"
echo "The highest-numbered file is $latest"
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.