Home > Blockchain >  Bash command to get start time and endtime from log file
Bash command to get start time and endtime from log file

Time:05-03

I need to get the start time and end time of from a log file which looks like the below format:

REQUEST     test 1 1651474077633    
.
.
.
.
REQUEST     test n  1651474676561   

I want to print start and end time. The time is in Unix format and I want to convert it into standard date and time format.

code which I tried:

cat ${FILENAME} | awk 'BEGIN {
   print strftime("Time = %m/%d/%Y %H:%M:%S", NF)
}'

But it prints all time.

I just want time for 1st entry and last entry.

CodePudding user response:

I think your code uses BEGIN and NF incorrectly.

Try the code below.

cat ${FILENAME} | awk '$1 == "REQUEST" { print strftime("Time = %m/%d/%Y %H:%M:%S", $4) }'

If you want to output only the first and last outputs:

cat ${FILENAME} | awk '
BEGIN { first = 1 }
$1 == "REQUEST" {
  if (first) {
    firsttime = $4
    first = 0
  }
  lasttime = $4
}
END {
  print strftime("First Time = %m/%d/%Y %H:%M:%S", firsttime)
  print strftime("Last  Time = %m/%d/%Y %H:%M:%S", lasttime)
}'

The numbers in the text in question do not seem to be in UNIX time, but you can check there.

CodePudding user response:

They're indeed valid posix epochs time, in milliseconds

just divide it by a 1000, and you'll get a reasonable timestamp - May 3rd, 2022 :

echo "${ccccc}" \
\
| gawk -be '
  function printtime(_,__,___,____) { 
      print \
          substr((____=RS)(RS="\n"),
          (__=sprintf("gdate  \47%5s Time = "(___\
                 )"\47",__,_*1e-3)) | getline _,
               RS*close(__)^(RS=____))_ 
 } 1<NF {
          __[  _]=$!(NF=NF) 
 }  END { 
          printtime(__[_^!_], "First", ___)
          printtime(__[( _)],  "Last", ___)

 }' ___='%D %T.%6N'  FS='^REQUEST[^t] test[ ] ([n]|[0-9] )[ ] ' | ecp
 
First Time = 05/03/22 00:55:57.458000
 Last Time = 05/03/22 00:55:57.462939
 
  • Related