Skip to content
Advertisement

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

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.

Advertisement

Answer

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
$
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement