I need to get the last 4 unique values from each record in a file. The file is delimited by comma and the number of columns can be different for different records. My input file.
$ cat last_cols.txt
F
F,B
F,B,A
F,B,A,F
F,B,A,F,B
F,B,A,F,B,G
F,B,A,F,B,G,E
F,B,A,F,B,G,E,F
F,B,A,F,B,G,E,F,E
F,B,A,F,B,G,E,F,E,B
F,B,A,F,B,G,E,F,E,B,A
F,B,A,F,B,G,E,F,E,B,A,D
F,B,A,F,B,G,E,F,E,B,A,D,F
F,B,A,F,B,G,E,F,E,B,A,D,F,E
F,B,A,F,B,G,E,F,E,B,A,D,F,E,E
F,B,A,F,B,G,E,F,E,B,A,D,F,E,E,D
$
My required output:
F,
B,F,
A,B,F,
A,B,F,
A,B,F,
A,B,F,G,
B,E,F,G,
B,E,F,G,
B,E,F,G,
B,E,F,G,
A,B,E,F,
A,B,D,E,
A,B,D,F,
A,D,E,F,
A,D,E,F,
A,D,E,F,
Attempt to get the output
awk -F, ' { split("",arr); for(i=NF;i>0;i--) { if(!$i in arr && length(arr)<4 ) arr[$i]=1 }; for(i in arr) printf("%s,",i); print "" } ' last_cols.txt
I just get empty lines.
Since this is going to be run in bash env, I welcome other solutions as well.