How to replac rows of one csv file from another csv file based on a condition in linux(using awk or any other)?

Viewed 68

first.csv

A , X 
B , Y
C , Z
D , X
E , X

second.csv

A , X , 1
D , X , 4
E , X , 6

required output.csv

A , X , 1
B , Y
C , Z
D , X , 4
E , X , 6

How to achieve above scenario like replace or adding rows from one CSV to another CSV file based on a condition in linux. Thanks in advance .

I tried below command

awk -F, '{getline f1 <"second.csv" ;if($2=="X"){ $0=f1}print $0}' OFS=, first.csv

but its not working . Replacing same record for all rows which satisfies the condition.

3 Answers

Could you please try following written and tested with shown samples GNU awk.

awk '
BEGIN{
  FS=OFS=" , "
}
FNR==NR{
  a[$1 OFS $2]=$3
  next
}
{
  $0=$0 (($1 OFS $2) in a?OFS a[$1 OFS $2]:"")
}
1
' second.csv first.csv

Explanation: Adding detailed explanation for above.

awk '                            ##starting awk program from here.
BEGIN{                           ##Starting BEGIN section from here.
  FS=OFS=" , "                   ##Setting field separator and output field separator as space comma space.
}
FNR==NR{                         ##Checking condition which will be TRUE when second.csv is being read.
  a[$1 OFS $2]=$3                ##Creating array a with index of 1st and 2nd field, value is $3.
  next                           ##next will skip all further statements from here.
}
{
  $0=$0 (($1 OFS $2) in a?OFS a[$1 OFS $2]:"")  ##Adding value of a with index of $1 OFS $2 if its present in a or add null.
}
1                                ##1 will print current line here.
' second.csv first.csv           ##Mentioning Input_file names here.

Another awk

$ awk -F, ' NR==FNR{ a[$1]=$0 ; next } ($1 in a ) { print a[$1] }  !($1 in a) { print } ' second.csv first.csv
A , X , 1
B , Y
C , Z
D , X , 4
E , X , 6
$

another approach

$ join file2 file1 -a2 | cut -d, -f1-3

A , X , 1
B , Y
C , Z
D , X , 4
E , X , 6
Related