Chen Xie
Chen Xie

Reputation: 4241

How to get the second latest file in a folder in Linux

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.

Upvotes: 9

Views: 12715

Answers (5)

Manoj Sahu
Manoj Sahu

Reputation: 2932

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

Will provide second latest file in the pattern you search.

Upvotes: 3

Santosh Dhere
Santosh Dhere

Reputation: 1

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

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

enjoy...!

Upvotes: -4

iruvar
iruvar

Reputation: 23364

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}'

Upvotes: 1

Jakub M.
Jakub M.

Reputation: 33827

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

ls -t | head -n 2 | xargs diff

Upvotes: 7

Cairnarvon
Cairnarvon

Reputation: 27762

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

Upvotes: 10

Related Questions