I have multiple files in a directory that follow the below pattern.
logA.log.$todayDate.$timeCreated
logA.log.07222020.084355
I want to compare the $timeCreated part of all the files in the directory created on todays date to obtain the latest version of the log file and then perform actions on that file once it is obtained.
Does anyone know the best way that I can do this?
-
1Using YMD instead of MDY has the advantage of not only being standard, but also sortable.– chorobaJul 22, 2020 at 16:40
-
Please add your own attempts to the question. A minimal example, with a list of file names and the one that should be selected, is also useful.– QuasímodoJul 22, 2020 at 16:44
2 Answers
You can just do:
set -- logA.log."$(date +%m%d%Y)".*
eval "latest=\${$#}"
(or shift "$(($# - 1))"; latest=$1
if you have religious objections to using eval
, though that particular use of eval
is perfectly safe).
As glob expansions are sorted lexically, given your HHMMSS
format, the last one in that list will be the latest one.
With zsh
:
(){latest=$argv[-1];} logA.log.${(%):-%D{%m%d%Y}}.*
Or:
(){latest=$1;} logA.log.${(%):-%D{%m%d%Y}}.*([-1])
${(%):-%D{%m%d%Y}}
uses the %
parameter expansion flag to expands %D{%m%d%Y}
as prompt expansion. You could of course replace it with "$(date +%m%d%Y)"
to make it more legible though that would involve forking an extra process and executing a separate utility.
Alternatively you could use zsh
's builtin strftime
command (in the zsh/datetime
module) as strftime -s today %m%d%Y
to fill the $today
variable with that timestamp.
some_command_that_takes_this_file_as_argument $(find . -iname "logA.log.$(date +%m%d%Y).[0-9]*" 2> /dev/null | sort -n | tail -1)
should do the trick
Edit: If you just want to use the newest logfile you could make it even easier:some_command_that_takes_this_file_as_argument $(ls -rt | grep ^logA.log. | tail -1)
-
-
sort -n
doesn't do what you think it does here.sort -n
interprets the lines as numbers and sorts based on those numbers. Here, all lines will be interpreted as0
as they start with./
which is not a number. The only reason it works is that in case of tie,sort
resorts to a lexical comparison of the full line. Note thatfind
will recurse into directories to find the files, and if it finds files in more than one directory, it will likely not work as the directory part will be taken into account in that lexical sorting. Jul 22, 2020 at 17:00