如何根据 linux 中的条件(使用 awk 或任何其他)从另一个 csv 文件替换一个 csv 文件的行?
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
需要output.csv
A , X , 1
B , Y
C , Z
D , X , 4
E , X , 6
如何实现上述场景,例如根据 linux 中的条件将一个 CSV 文件中的行替换或添加到另一个 CSV 文件。 提前致谢 .
我试过下面的命令
awk -F, '{getline f1 <"second.csv" ;if(=="X"){ [=14=]=f1}print [=14=]}' OFS=, first.csv
但它不起作用。为满足条件的所有行替换相同的记录。
您能否尝试按照所示示例 GNU awk
.
编写并测试
awk '
BEGIN{
FS=OFS=" , "
}
FNR==NR{
a[ OFS ]=
next
}
{
[=10=]=[=10=] (( OFS ) in a?OFS a[ OFS ]:"")
}
1
' second.csv first.csv
说明: 为以上添加详细说明。
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[ OFS ]= ##Creating array a with index of 1st and 2nd field, value is .
next ##next will skip all further statements from here.
}
{
[=11=]=[=11=] (( OFS ) in a?OFS a[ OFS ]:"") ##Adding value of a with index of OFS if its present in a or add null.
}
1 ##1 will print current line here.
' second.csv first.csv ##Mentioning Input_file names here.
另一个 awk
$ awk -F, ' NR==FNR{ a[]=[=10=] ; next } ( in a ) { print a[] } !( in a) { print } ' second.csv first.csv
A , X , 1
B , Y
C , Z
D , X , 4
E , X , 6
$
另一种方法
$ join file2 file1 -a2 | cut -d, -f1-3
A , X , 1
B , Y
C , Z
D , X , 4
E , X , 6
first.csv
A , X
B , Y
C , Z
D , X
E , X
second.csv
A , X , 1
D , X , 4
E , X , 6
需要output.csv
A , X , 1
B , Y
C , Z
D , X , 4
E , X , 6
如何实现上述场景,例如根据 linux 中的条件将一个 CSV 文件中的行替换或添加到另一个 CSV 文件。 提前致谢 .
我试过下面的命令
awk -F, '{getline f1 <"second.csv" ;if(=="X"){ [=14=]=f1}print [=14=]}' OFS=, first.csv
但它不起作用。为满足条件的所有行替换相同的记录。
您能否尝试按照所示示例 GNU awk
.
awk '
BEGIN{
FS=OFS=" , "
}
FNR==NR{
a[ OFS ]=
next
}
{
[=10=]=[=10=] (( OFS ) in a?OFS a[ OFS ]:"")
}
1
' second.csv first.csv
说明: 为以上添加详细说明。
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[ OFS ]= ##Creating array a with index of 1st and 2nd field, value is .
next ##next will skip all further statements from here.
}
{
[=11=]=[=11=] (( OFS ) in a?OFS a[ OFS ]:"") ##Adding value of a with index of OFS if its present in a or add null.
}
1 ##1 will print current line here.
' second.csv first.csv ##Mentioning Input_file names here.
另一个 awk
$ awk -F, ' NR==FNR{ a[]=[=10=] ; next } ( in a ) { print a[] } !( in a) { print } ' second.csv first.csv
A , X , 1
B , Y
C , Z
D , X , 4
E , X , 6
$
另一种方法
$ join file2 file1 -a2 | cut -d, -f1-3
A , X , 1
B , Y
C , Z
D , X , 4
E , X , 6