Below is how my file looks like (sorted on $3):
name_1|G1026|2017-08-27|2017-08-27|2017-09-02|19|19|21
name_2|G1566|2018-05-05|2018-05-05|2018-06-11|51|51|2B
name_2|G2124|2018-06-11|2018-06-11|2018-06-11|51|19|2B
name_2|G2125|2018-06-11|2018-06-11|2018-06-15|51|19|41
name_1|G4391|2020-08-14|2020-08-14|2020-08-20|19|19|21
name_1|G4392|2020-08-14|2020-08-20|2020-08-20|19|51|21
The fields separator is |. I am trying to add one extra column $9 to this file based on the existing columns. For multiple instances of names in $1, I want to apply the conditions below:
cond1 && (cond2 || cond3 || cond4) && (!cond5)
Let prev and cur be two rows with the same first field, a non-empty third field, and cur following prev. Rows 1,5 or 5,6 are pairs of such rows with first field name_1. Rows 2,3 and 3,4 are pairs of such rows with first field name_2.
Let delta = number-of-days(prev.$5 - cur.$4) be the number of days prev.$5 is past cur.$4.
The conditions are:
cond1 = (0 <= delta <= 2 days)for example, for the 1st instance of
name_1(1st row), check ifprev.$5from 1st instance (1st row) is between 0 and 2 days latercur.$4from 2nd instance (6th row).cond2 = (prev.$6 == 51)cond3 = (cur.$7 == 51)cond4 = (cur.$8 == "2B" || cur.$8 == 41)cond5 = (prev.$6 == 19 && cur.$7 == 51 && cur.$8 == 21)
If these conditions are met then add column $9 to the first of the two rows so the output would be like the one given below.
name_1|G1026|2017-08-27|2017-08-27|2017-09-02|19|19|21
name_2|G1566|2018-05-05|2018-05-05|2018-06-11|51|51|2B|group1
name_2|G2124|2018-06-11|2018-06-11|2018-06-11|51|19|2B|group2
name_2|G2125|2018-06-11|2018-06-11|2018-06-15|51|19|41
name_1|G4391|2020-08-14|2020-08-14|2020-08-20|19|19|21
name_1|G4392|2020-08-14|2020-08-20|2020-08-20|19|51|21
The added column starts with group1. The leading number increments each time a column is added.
If the required prev.$ and cur.$ values were in a single line then I could have have applied the below code:
awk -F "|" '{if ($1=="name_1" && (($5-$4)<=2) && ($6==51||$7==51||$8==2B|41) &&($6!=19 && $7!=51 && $8!=21)) print $9="group1"}' OFS="|" file
Any lead on how to solve this with awk would be highly appreciated!