繁体   English   中英

使用awk将1列与两个文件中的另一列匹配,然后对匹配记录进行日期减法

[英]using awk match 1 column to another in two files and then do date subtraction for the matching records

使用awk将1列与两个文件中的另一列相匹配,然后对匹配记录进行日期减法(以天为单位)。

假设我有两个文件

文件1:

123,2-jul-2016
124,2-jul-2018

文件2:

123,2-jul-2015
124,2-jul-2017

如果匹配则给我输出为

123,366
124,366

谢谢您的帮助

您可以尝试以下吗?

awk '
BEGIN{
  FS=OFS=","
  num=split("jan,feb,mar,apr,may,jun,jul,aug,oct,nov,dec",month,",")
  for(i=1;i<=num;i++){
    daymonth[month[i]]=i}
}
FNR==NR{
  a[$1]=$2
  next
}
($1 in a){
  split($2,array2,"-")
  split(a[$1],array1,"-")
  print $1,(mktime(sprintf("%d %d %d 0 0 0 0",array2[3],daymonth[array2[2]],array2[1]))-\
            mktime(sprintf("%d %d %d 0 0 0 0",array1[3],daymonth[array1[2]],array1[1])))\
                  /86400
}'  Input_file2   Input_file1

使用GNU awk的时间功能:

$ cat tst.awk
BEGIN {
    FS  = "[,-]"
    OFS = ","
}
{
    mthNr = (index("janfebmaraprmayjunjulaugsepoctnovdec",$3)+2)/3
    date  = sprintf("%04d %02d %02d 00 00 00", $4, mthNr, $2)
    secs  = mktime(date)
}
NR==FNR {
    end[$1] = secs
    next
}
{
    print $1, int((end[$1] - secs) / (24*60*60))
}

$ awk -f tst.awk file1 file2
123,366
124,365

您的问题的预期输出是错误的,因为它没有说明2016年2月或2015年的leap日,例如,假设3与4之间的差是2而不是1。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM