Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

awk or sed change field of file based on another input file

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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) {
            v=arr[i] + 1
            $v=1
        }
     print
    }
' slots2change.csv matrix.csv
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading