Reputation:
I have two text files named as a.txt
and b.txt
, that contain data in the following format as depicted below
year mn dt hr:mn:sec
xxxx-xx-xx xx:xx:xx.xxxxxx
My a.txt file is
2019-01-01 00:58:49.925000
2019-01-01 01:48:39.665000
2019-01-01 15:42:18.955000
2019-01-01 18:40:49.915000
2019-01-01 18:47:00.735000
2019-01-01 21:07:49.255000
2019-01-01 21:52:29.055000
2019-01-02 03:19:54.955000
2019-01-02 07:41:27.845000
2019-01-02 18:52:32.995000
And b.txt file contains
2019-01-01 00:58:50.565000
2019-01-01 01:48:39.915000
2019-01-01 04:09:53.705000
2019-01-01 06:28:07.515000
2019-01-01 15:43:13.455000
2019-01-01 18:40:53.255000
2019-01-01 18:47:04.005000
2019-01-01 18:47:03.975000
2019-01-01 21:07:53.725000
2019-01-01 21:52:37.195000
2019-01-02 07:41:34.255000
2019-01-02 19:41:08.865000
Additionally, each of the text files (a.txt and b.txt) contain 14 number of rows including the space.
Now I want to calculate the time difference between each row (a.txt-b.txt
) in seconds and i want to append the rows to a new text file c.txt which should only contain rows with time difference is between 3 to 18 second.
I did something like as follows:
#!/bin/sh
a=`cat a.txt`
b=`cat b.txt`
awk '{print $a-$b}'
Upvotes: 2
Views: 802
Reputation: 203665
Using GNU awk for mktime() based on one possible interpretation of your question:
$ cat tst.awk
!NF { next }
{ gsub(/[-:]/," ") }
NR==FNR {
file1[NR] = $0
next
}
FNR in file1 {
diff = mktime($0) - mktime(file1[FNR])
if ( (3 <= diff) && (diff <= 18) ) {
print diff
}
}
$ awk -f tst.awk a.txt b.txt
4
4
4
8
7
Obviously just add > c.txt
to redirect the output.
If that's not what you need then edit your question to clarify your requirements and provide the expected output given your posted sample input.
Upvotes: 2
Reputation: 27225
Convert each date to unix time using date -d "2019-01-01 …" +%s
. Then subtract the unix times. This considers only whole seconds. Your dates include fractions of seconds. If you want to use the fractions too, change +%s
to +%s.%N
.
The following script includes all of your extra requirements, see the comment section of this answer.
paste a.txt b.txt |
awk '
function inSecs(date) {
cmd = "date -d \""date"\" +%s"
cmd | getline unixTime
close(cmd)
return unixTime
}
{
if (NF == 4) {
diff = inSecs($1" "$2) - inSecs($3" "$4)
if (3 <= diff && diff <= 18)
print $1 " " diff "sec"
}
}'
Upvotes: 1