Whilst monitoring logging I have to go to my log files, order by written date, so I can then see the name of the log file for the most-recent execution of my application.
I assume this means that the application writes log files like this:
- AFile1.log
- AFile2.log
- AFile3.log
- AFilex.log
Is there any way, given a directory and sub-string, to return the name of the file containing that sub-string, which was most-recently written to?
I assume this sub-string is the partial file name, AFile, and not a string to find within a log file.
I wanted to return the most recent log containing the file name "AFile", it'd return AFile2.log?
From the manual on ls
(man ls
):
-t sort by modification time, newest first
-l use a long listing format
So, to first see this in action, we might use ls -lt
to get a long directory listing with the newest modification first.
$ ls -lt AFile*.log
-rw-r--r-- 1 root root 27254 May 23 09:00 AFile2.log
-rw-r--r-- 1 root root 29599 May 22 21:15 AFile1.log
Good. This works. (We know we do not want the long listing; we are just using -l
to witness that the desired output is correct.) Now, how do we grab just the first line? If we do not know how to do this, the use of apropos
is often beneficial. So let's try it.
$ apropos "first"
Among the many lines of output, we see the following:
head (1) - output the first part of files
Ok, so let's look at the man page for head
(man head
or man 1 head
).
-n, --lines=[-]K
print the first K lines instead of the first 10; with the lead‐
ing '-', print all but the last K lines of each file
Connecting the dots, and using a pipe, we get the latest file.
$ ls -t AFile*.log | head -n 1
AFile2.log
The pipe is the construct using the |
character, which passes the output of ls -t AFile*.log
to head -n 1
.