bash q4u - how to append value in different file matching on userid in column1

Viewed 22

Thanks for looking. I've tried various awk, sed, paste, cut commands - arg. Looking for a bash solution.

I have two files - file1 is a csv of attributes for each user, beginning with userid in col1. in file2 lists userid and another unique attribute, matching each userid in file1

how can i write a 'for i in' , or 'while read line' on file1, store the userid on each line in file1 on col1 , search file2 for the userid and then store the 2nd value (listed like this userid,uniqueAttribute), and that append that uniqueAttribute at the end of the stored line in file1 (or a new file with the entire line from file1,uniqueAttribute.

1 Answers

file1.csv:

userid,first_name
bob,Robert
jane,Janice

file2.csv:

userid,unicorn
bob,yes
jane,no

and here super simple script that correlates the two:

while IFS=, read userid first_name
do
    echo "$userid,$first_name,$(grep ^$userid file2.csv | cut -d, -f2)"
done < file1.csv 

and the output would be:

userid,first_name,unicorn                                                                                              
bob,Robert,yes                                             
jane,Janice,no                                                                                                         

You asked for a loop but join would give you the same result:

join -t, file1.csv file2.csv
Related