Issue
I have a sparse matrix ("matrix.csv") with 10k rows and 22 columns (1st column is "user", and the rest columns are called "slots" and contain 0s or 1s), like this:
user1,0,0,0,1,0,0,0,1,0,1,0,0,...,0
user2,0,1,0,0,0,0,0,0,0,0,0,1,...,0
user3,0,0,0,0,0,0,1,0,0,0,1,0,...,0
...
Some of the slots that contain a "0" should be changed to contain a "1". I have another file ("slots2change.csv") that tells me which slots should be changed, like this:
user1,3
user3,21
...
So for user1, I need to change slot3 to contain a "1" instead of a "0", and for user3 I should change slot21 to contain a "1" instead of a "0", and so on.
Expected result:
user1,0,0,1,1,0,0,0,1,0,1,0,0,...,0
user2,0,1,0,0,0,0,0,0,0,0,0,1,...,0
user3,0,0,0,0,0,0,1,0,0,0,1,0,...,1
...
How can I achieve this using awk or sed?
tried
awk -F"," 'NR==FNR{user=$1;slot2change=$2} NR!=FNR; /user/ slot2change==0{print $0} ' slots2change.csv matrix.csv
but I feel I am still far from a correct command...
Solution
Like this:
awk 'BEGIN{FS=OFS=","}
NR==FNR{arr[$1]=$2;next}
NR!=FNR {for (i in arr)
if ($1 == i) {
F=arr[i] + 1
$F=1
}
print
}
' slots2change.csv matrix.csv
Answered By - Gilles Quénot Answer Checked By - Mildred Charles (WPSolving Admin)