2

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 Answers3

3

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.
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
3

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
$
stack0114106
  • 8,534
  • 3
  • 13
  • 38
2

another approach

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

A , X , 1
B , Y
C , Z
D , X , 4
E , X , 6
karakfa
  • 66,216
  • 7
  • 41
  • 56