Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

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

    filename_20120101.dat
    filename_20120102.dat
    filename_20120103.dat

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
add comment

2 Answers

up vote 3 down vote accepted

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

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

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])
filename_8.dat
% echo filename_*.dat(n[-1])
filename_17.dat

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:

latest=(filename_*.dat[-1])
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
add comment

Your Answer

 
discard

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.