Home > OS >  How to use grep or awk to get the time difference between 2 reads in the log
How to use grep or awk to get the time difference between 2 reads in the log

Time:03-05

Hi I basically want to know the time difference between transactions. Below is an example:

1000 mem_rd
1100 mem_wr
1200 mem_rd
1300 mem_wr
1500 mem_rd
1650 mem_rd

The first column is time and 2nd is transaction type. I only want to see mem_rd and the time difference between 2 transactions using any command line code. Below is the expected output:

0   mem_rd
200 mem_rd
300 mem_rd
150 mem_rd

CodePudding user response:

Here's a one-line solution:

cat file.txt | awk 'BEGIN {t0=0}; /mem_rd/ {t1=$1; if(t0==0) t0=t1; printf("%-3d %s\n", t1-t0, $2); t0=t1}'

Or the same thing, but written in a script file to make it more readable:

$ cat script.awk
BEGIN {t0=0}
/mem_rd/ {
  t1=$1;
  if(t0==0)
    t0=t1;
  printf("%-3d %s\n", t1-t0, $2);
  t0=t1}

$ awk -f script.awk file.txt
0   mem_rd
200 mem_rd
300 mem_rd
150 mem_rd
  • Related