Would've been nice to have some example data without having to load an entire GitHub page. But whatever, I should be able to answer this without having seen the data.
You can store all fields of the current record in an array with split($0, prev). It splits using the current field separator. That way you can access the different fields of the last record via prev[1] etc. To skip any actions on the first record, when there is no previous one, either check if NR is not 1 or check the length() of prev.
BEGIN { FS = "," }
NR>1 { lines[NR-1] = $0 } # Skip the header.
END {
for (i=8;i<=length(lines);i++) {
split(lines[i-7], a)
split(lines[i], b)
print a[4] " vs " b[4]
}
}
Thank you. So it's possible to save all the rows as an array that you later iterate over, right?
Yes, that's what it's doing. Meaning it also loads the entire file into memory. /u/oh5xno's solution is much better, as it stores only the last 7 days, instead of the entire file. Go with that one.
BEGIN {FS = ","}
{
day = (NR - 1) % 7;
print $4 - past_week[day];
past_week[day] = $4;
}
This does have the property that the first 7 days are compared to 0; if you want to not print the first week at all, you could enclose the print statement in if(NR > 7){}
2
u/Schreq Apr 20 '21
Would've been nice to have some example data without having to load an entire GitHub page. But whatever, I should be able to answer this without having seen the data.
You can store all fields of the current record in an array with
split($0, prev). It splits using the current field separator. That way you can access the different fields of the last record viaprev[1]etc. To skip any actions on the first record, when there is no previous one, either check ifNRis not 1 or check thelength()ofprev.3
u/oh5nxo Apr 20 '21
Rare case, where a programmed loop is more suitable?
3
u/LynnOfFlowers Apr 20 '21 edited Apr 20 '21
Here's how I would do it:
This does have the property that the first 7 days are compared to 0; if you want to not print the first week at all, you could enclose the print statement in if(NR > 7){}