How is millisecond subtracted from AWK - script

I am trying to create an awk script to subtract milliseconds between two entries, for example:

At the command line, I can do this:

Input:

06:20:00.120 06:20:00.361 06:20:15.205 06:20:15.431 06:20:35.073 06:20:36.190 06:20:59.604 06:21:00.514 06:21:25.145 06:21:26.125 

Command:

 awk '{ if ( ( NR % 2 ) == 0 ) { printf("%s\n",$0) } else { printf("%s ",$0) } }' input 

I will get this:

 06:20:00.120 06:20:00.361 06:20:15.205 06:20:15.431 06:20:35.073 06:20:36.190 06:20:59.604 06:21:00.514 06:21:25.145 06:21:26.125 

To subtract milliseconds correctly:

 awk '{ if ( ( NR % 2 ) == 0 ) { printf("%s\n",$0) } else { printf("%s ",$0) } }' input| awk -F':| ' '{print $3, $6}' 

And to avoid negative numbers:

 awk '{if ($2<$1) sub(/00/, "60",$2); print $0}' awk '{$3=($2-$1); print $3}' 

The goal is to get the following:

 Call 1 0.241 ms Call 2 0.226 ms Call 3 1.117 ms Call 4 0.91 ms Call 5 0.98 ms 

And finally, the middle one.

I could accomplish this, but command by command. I do not know how to place this in a script.

Please, help.

+4
source share
3 answers

One way: awk :

The contents of script.awk :

 ## For every input line. { ## Convert formatted dates to time in miliseconds. t1 = to_ms( $0 ) getline t2 = to_ms( $0 ) ## Calculate difference between both dates in miliseconds. tr = (t1 >= t2) ? t1 - t2 : t2 - t1 ## Print to output with time converted to a readable format. printf "Call %d %s ms\n", ++cont, to_time( tr ) } ## Convert a date in format hh:mm:ss:mmm to miliseconds. function to_ms(time, time_ms, time_arr) { split( time, time_arr, /:|\./ ) time_ms = ( time_arr[1] * 3600 + time_arr[2] * 60 + time_arr[3] ) * 1000 + time_arr[4] return time_ms } ## Convert a time in miliseconds to format hh:mm:ss:mmm. In case of 'hours' or 'minutes' ## with a value of 0, don't print them. function to_time(i_ms, time) { ms = int( i_ms % 1000 ) s = int( i_ms / 1000 ) h = int( s / 3600 ) s = s % 3600 m = int( s / 60 ) s = s % 60 # time = (h != 0 ? h ":" : "") (m != 0 ? m ":" : "") s "." ms time = (h != 0 ? h ":" : "") (m != 0 ? m ":" : "") s "." sprintf( "%03d", ms ) return time } 

Run the script:

 awk -f script.awk infile 

Result:

 Call 1 0.241 ms Call 2 0.226 ms Call 3 1.117 ms Call 4 0.910 ms Call 5 0.980 ms 
+2
source

Using awk :

 awk ' BEGIN { cmd = "date +%s.%N -d " } NR%2 { cmd $0 | getline var1; next } { cmd $0 | getline var2; var3 = var2 - var1; print "Call " ++i, var3 " ms" } ' file Call 1 0.241 ms Call 2 0.226 ms Call 3 1.117 ms Call 4 0.91 ms Call 5 0.98 ms 
+3
source

If you are not attached to awk:

 to_epoch() { date -d "$1" "+%s.%N"; } count=0 paste - - < input | while read t1 t2; do ((count++)) diff=$(printf "%s-%s\n" $(to_epoch "$t2") $(to_epoch "$t1") | bc -l) printf "Call %d %5.3f ms\n" $count $diff done 
+2
source

Source: https://habr.com/ru/post/1392481/


All Articles