Bash
在 bash 中使用 awk 比較日期
我有一個文件,每一行都有一些資訊和一個日期,所以我想要的是在給定日期之後列印帶有日期的行。我使用這個 awk 命令
sort -t$'|' -k5 $2 | awk -F '|' -v DatedAfter=$4 '!/^#/ && $5>=DatedAfter {print $0}'
在哪裡 $ 4 is a date in DD/MM/YYYY format given and $ 2 是我使用的格式如下的文件。
1099511628908|Chen|Wei|female|02/08/1989|2010-05-24T20:52:26.582+0000|27.98.244.108|Firefox 1099511633435|Smith|Jack|male|19/04/1978|2010-05-26T03:45:11.772+0000|50.72.193.218|Internet Explorer
所以當我執行我的程式碼時,我得到了這些結果。
./tool.sh --born-since 17/11/1983 -f events.dat 1099511629352|Nunez|Jorge|female|17/11/1986|2011-04-04T05:54:52.693+0000|201.221.59.59|Opera|Facebook 1099511638548|Phan|Don|female|17/5/1981|2011-04-19T00:14:15.041+0000|112.72.79.36|Opera|Flickr 1099511638387|Znaimer|Moses|male|17/8/1980|2011-05-12T01:03:01.291+0000|94.199.19.90|Internet Explorer|Youtube 6597069776449|Svensson|Ernst|male|30/11/1981|2012-04-22T05:16:03.557+0000|31.31.166.207|Opera|Youtube 2199023258994|Ngoche|Alex Obanda|female|30/9/1987|2011-07-22T16:36:27.420+0000|41.81.41.21|Opera|Google+ 7696581405294|Dobrunov|Aleksandr|male|31/12/1989|2012-05-15T05:46:31.439+0000|31.25.243.122|Internet Explorer|LinkedIn 2199023266450|Charoenpura|Somchai|male|4/12/1987|2011-08-30T20:34:41.524+0000|110.76.154.132|Mozilla|Youtube 3298534890514|Chen|Hsin|male|4/4/1988|2011-11-03T16:32:44.238+0000|115.42.116.30|Safari|Google+ 2199023261081|Ben Dhifallah|Karim|male|6/4/1980|2011-06-11T02:24:17.194+0000|193.95.74.75|Chrome|Twitter 8796093024550|Yang|Lei|male|7/1/1990|2012-07-15T17:14:42.186+0000|1.4.92.176|Mozilla|Facebook
如果日期在其中
YYYYMMDD
(那麼它們將按字典和數字順序)會更容易。您可以gensub
在 awk 中使用它。例如:awk -F"|" -v d="$d" -v dp='(..)/(..)/(....)' 'BEGIN {gensub(dp, "\3\2\1", d)} {dt=$5; gensub(dp, "\3\2\1", dt);} dt >= d' foo
該
d
變數保存用於比較的日期,並dp
保存與日期匹配的模式DD/MM/YYYY
。然後用gensub
,我們移動那些(\3
,\2
,\1
分別是匹配的組((....)
,第二個(..)
,第一個(..)
)。與每行的第五個欄位相同,我們複製它以避免修改輸入。我用更多日期擴展了您的範例輸入:
1099511628908|Chen|Wei|female|02/08/1989|2010-05-24T20:52:26.582+0000|27.98.244.108|Firefox 1099511633435|Smith|Jack|male|19/04/1978|2010-05-26T03:45:11.772+0000|50.72.193.218|Internet Explorer 1099511633435|Smith|Jack|male|19/04/1979|2010-05-26T03:45:11.772+0000|50.72.193.218|Internet Explorer 1099511633435|Smith|Jack|male|19/04/1977|2010-05-26T03:45:11.772+0000|50.72.193.218|Internet Explorer 1099511633435|Smith|Jack|male|19/04/1980|2010-05-26T03:45:11.772+0000|50.72.193.218|Internet Explorer 1099511633435|Smith|Jack|male|19/03/1978|2010-05-26T03:45:11.772+0000|50.72.193.218|Internet Explorer
並得到這個結果
19/04/1978
用於比較:1099511633435|Smith|Jack|male|19/04/1978|2010-05-26T03:45:11.772+0000|50.72.193.218|Internet Explorer 1099511633435|Smith|Jack|male|19/04/1979|2010-05-26T03:45:11.772+0000|50.72.193.218|Internet Explorer 1099511633435|Smith|Jack|male|19/04/1980|2010-05-26T03:45:11.772+0000|50.72.193.218|Internet Explorer