Bash – Leap year – extrapolating value

bashshelltable

I have some tables (table.txt) as follow:

YEAR MONTH DAY RES
1971 1     1   1345
1971 1     2   1265
1971 1     3   1167

The length of each time series goes from 1.1.1971 until 31.12.2099. Unfortunately, some time series are missing leap years and their values (e.g. year 1972 is a leap year so the month of February should have 29 days, but my time series just have 28 days in February 1972). For examples in my current tables the end of the February month in 1972 is presented as follow:

YEAR MONTH DAY RES
1972 2     27  100
1972 2     28  101
1972 3     1   102

This is wrong, cause it´s not accounting any leap year. Instead of that I would like to include in my time series each missing days (obviously the 29th of February) of every leap years in my time series, by extrapolating the value with the previous and next day, as follow:

YEAR MONTH DAY RES
1972 2     27  100
1972 2     28  101
1972 2     29  101.5
1972 3     1   102

Is there a way to do that using shell/bash?

Best Answer

Maybe something like:

awk '
  function isleap(y) {
    return y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)
  }
  $2 == 3 && $3 == 1 && isleap($1) && last_day != 29 {
    print $1, 2, 29, (last_data + $4) / 2
  }
  {print; last_day = $3; last_data = $4}' file
Related Question