我有一个文件,每一行都有一些信息和日期,所以我想要的是打印给定日期之后的日期行。我使用这个 awk 命令
sort -t$'|' -k5 $2 | awk -F '|' -v DatedAfter=$4 '!/^#/ && $5>=DatedAfter {print $0}'
其中 $4 是给定的 DD/MM/YYYY 格式的日期,$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
答案1
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
答案2
怎么样
DT="01/08/1989"
awk -F\| -vDT=${DT:6}${DT:3:2}${DT:0:2} 'substr($5, 7) substr($5, 4, 2) substr($5, 1, 2) > DT' file
1099511628908|Chen|Wei|female|02/08/1989|2010-05-24T20:52:26.582+0000|27.98.244.108|Firefox