gpt4 book ai didi

linux - 比较两个文件并合并数据

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:48:16 26 4
gpt4 key购买 nike

我有以下文件,

total.txt

order1,5,item1
order2,6,item2
order3,7,item3
order4,6,item4
order8,9,item8

已更改.txt

order3,8,item3
order8,12,item8

total.txt为总订单数据,changed.txt为最近变动数据。我想将最近的更改与总计合并,我希望输出为,

输出.txt

order1,5,item1
order2,6,item2
order3,8,item3
order4,6,item4
order8,12,item8

注意:total.txt 的第 2 列(第 3 和第 5)行已使用已更改的 .txt 文件更新

我已经使用下面的nawk 来比较第一个coulmn,但无法将它打印到输出文件。请帮助完成以下命令

nawk -F","'NR==FNR {a[$1]=$2;next} ($1 in a) "print??"' total.txt changed.txt

最佳答案

另一个awk

awk -F, 'FNR==NR {a[$1]=$0;next} {print (a[$1]?a[$1]:$0)}' changed.txt total.txt
order1,5,item1
order2,6,item2
order3,8,item3
order4,6,item4
order8,12,item8

它是如何工作的?

awk -F, '                       # set field separator to ","
FNR==NR { # run this only on first file "changed.txt"
a[$1]=$0 # store "changed.txt" in array "a" using first field as index
next # skip to next record
}
{ # run this when second file is read "total.txt"
print (a[$1]?a[$1]:$0) # if filed exist in "changed" use that, else use "total"
}' changed.txt total.txt # read these files

关于linux - 比较两个文件并合并数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19883209/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com