[英]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.