Need help with UNIX command to get the latest file from list of files with timestamp

Hi All,

I have list of files like below with name abcxyz.timestamp. I need a unix command to pick the latest file from the list of below files. Here in this case the lates file is abcxyz.20190304103200 . I have used this unix command "ls abcxyz*|tail -1" but i heard that it is not the appropriate one which may not be successful all the time.I was told to use a command by sorting the files based on the timestamp. Please do the needful.

abcxyz.20190304103200
abcxyz.20190303131348
abcxyz.20190303115704
abcxyz.20190227153924
abcxyz.20190215171513
abcxyz.20190228123958

Thanks
Rakesh

That depends on what you call "latest". If you can make ABSOLUTELY sure the name's time stamp is correct, can't be tampered with, and coincides with the file creation, why not use it? If you don't, read man ls on the -t option.

1 Like

Using the filenames as the ONLY time reference:

newest=$( ls abcd*|  sort -n -k2 -t '.' | tail -1 )

Using file mtimes (last time written to, the default for ls -l )

newest=$( ls -rt '.' | tail -1 )

The inode time ls -c abcd* is another internal time kept. This is almost always the file creation time. File creation time (birth time) is not universal, older UNIXes filesystems do not support it.

Since your question vague this is about the best we can do for you. We need your shell and your OS ( uname -a shows this) to do better.

1 Like