Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

shell

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.

like image 880
Chen Xie Avatar asked May 17 '13 21:05

Chen Xie


People also ask

How do I see the second last line of a file in Linux?

To look at the last few lines of a file, use the tail command. tail works the same way as head: type tail and the filename to see the last 10 lines of that file, or type tail -number filename to see the last number lines of the file. Try using tail to look at the last five lines of your .

How do I move the latest file in Linux?

The ls command lists files in the current working directory. To move a file from one directory to another, use mv. The use of the mv command changes the name of the file from oldname to newname. Each of the commands listed above have options that may be specified on the command line.

How do I get the latest log file in Linux?

/var/log. This is such a crucial folder on your Linux systems. Open up a terminal window and issue the command cd /var/log. Now issue the command ls and you will see the logs housed within this directory (Figure 1).


2 Answers

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
like image 50
Cairnarvon Avatar answered Sep 21 '22 20:09

Cairnarvon


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

ls -t | head -n 2 | xargs diff
like image 23
Jakub M. Avatar answered Sep 23 '22 20:09

Jakub M.