使用命令行工具根据唯一ID聚合CSV数据

我想集合数据从一个CSV文件到另一个,使用命令行工具,如bashsedawk等等中的每个文件中的每一行与一个唯一的ID开始在第1列,并且如果在所述目的地的行该ID相匹配,则行应该被替换,否则应该附加。输入数据未排序,但结果的排序顺序无关紧要,因此如果有帮助,文件可以作为脚本的一部分进行排序。

例如,给定当前状态aggregate.csv

1,olddata
3,olddata
2,olddata

和文件new.csv

4,newdata
2,changeddata
3,changeddata

我想aggregate.csv出来如下(以任何排序顺序):

1,olddata
2,changeddata
3,changeddata
4,newdata

这些行可能包含大量列,因此一次替换一个单元格并不理想。CSV 保证不包含引用的换行符,因此逐行搜索并一次替换整行是一种有效的方法。

抱歉,如果这是重复的,但我找不到另一个完全使用这种 CSV 合并方法的问题。

我已经尝试调整这个问题的答案,但它首先需要通过逐行解析两个文件、排序、删除重复项和保存来生成所有 ID 的“模板文件”——我希望有一种更简单的方法是可能的。

这个问题在 sed 和 awk 中有答案,我也复制了这些答案,并管理了正则表达式替换部分,但不是在不存在匹配的情况下向文件追加新行的方法。

谢谢!

回答

使用任何 awk:

$ awk -F, '!seen[$1]++' new agg
4,newdata
2,changeddata
3,changeddata
1,olddata

或使用 GNU 排序-s

$ sort -ust, -k1,1 new agg
1,olddata
2,changeddata
3,changeddata
4,newdata

  • Do you understand them both? If not, feel free to ask questions. If so then which one are you going to use in your code? In general you shouldn't just accept the first answer you get as an answer that produces the expected output from a given sample input set is the starting point to identifying the best (or even a correct) solution, not the end point, and accepting any answer discourages other people from posting alternative answers so then it's your loss. It's usually best to wait a few hours or a day to see what answers you get and THEN accepting one.
  • Ah OK, so '!seen[$1]++' alone is enough to say "if field 1 doesn't already exist in the array, then add it to the array and carry on processing, but if it does, stop processing this line" without anything special about "seen". Gotcha, thanks!

以上是使用命令行工具根据唯一ID聚合CSV数据的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>