8

Found several posts like this one to tell how to find the latest file inside of a folder.

My question is one step forward, how to find the second latest file inside the same folder? The purpose is that I am looking for a way to diff the latest log with a previous log so as to know what have been changed. The log was generated in a daily basis.

5 Answers 5

10

Building on the linked solutions, you can just make tail keep the last two files, and then pass the result through head to keep the first one of those:

ls -Art | tail -n 2 | head -n 1
7

To do diff of the last (lately modified) two files:

ls -t | head -n 2 | xargs diff
2

ls -dt {{your file pattern}} | head -n 2 | tail -n 1

Will provide second latest file in the pattern you search.

1

Here's a stat-based solution (tested on linux)

for x in ./*; 
do
if [[ -f "$x" ]]; then
  stat --printf="%n %Y\n" "$x"; fi;
done | 
sort -k2,2 -n -r | 
sed -n '2{p;q}'
-4

Here's the command returns you latest second file in the folder

ls -lt | tail -n 1 | head -n 2

enjoy...!

1
  • This solution is close...look down for Jakub M. for the right one.
    – Punkman
    Commented Jun 9 at 7:19

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