Unix & Linux Asked by e77x on November 28, 2021
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?
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.
Answered by Stéphane Chazelas on November 28, 2021
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)
Answered by Garo on November 28, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP