0

I have 2 .csv files, file1.csv and file2.csv. Say a line from file2.csv has the same 1st field as a line from file1.csv. I would like the full line from file1.csv to replace the full line from file2.csv. I have tried a script to delete the line from file2 and add the line from file1. I've tried to awk the lines from file2 that DON'T contain the match, and then add from file1but failed.

file1.csv:

1,2,3
2,3,4
3,4,5

file2.csv

6,7,8
7,8,9
1,9,0

Desired result:

6,7,8
7,8,9
1,2,3
  • Your title says "append" but I find that misleading; the body says (reworded) "replace entire liens from file2 with matching lines from file1"; where does "append" come in? – Jeff Schaller Sep 30 '18 at 18:35
  • Caveats: I will NOT know the values that match. I've been trying to run "while read do" inserting the variable value in different ways. Also the number of fields will vary by line, but the matching values will always be in the first field. Please help! – Trevor Martin Sep 30 '18 at 18:36
  • Jeff, by "append" I was simply referring to the fact that the first field will remain while the rest are "updated." I assumed that replacing the entire line would be easiest (since the replacement line is one with the same value in the first field) – Trevor Martin Sep 30 '18 at 18:40
  • What if you have more than one match in the first field? – user88036 Sep 30 '18 at 19:36
  • Luckily the type of data I'm dealing with doesn't allow for that, because I can see how that would be a problem. – Trevor Martin Oct 1 '18 at 5:59
1

For the simple input files that you have posted:

$ awk -F, 'NR==FNR {a[$1]=$0; next} $1 in a {$0=a[$1]} 1' file1.csv file2.csv
6,7,8
7,8,9
1,2,3

Note that in general, the CSV format allows for quoted embedded separators and other nasties that may make a simple Awk script unsuitable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.