gpt4 book ai didi

unix - Unix:通过保留第一个文件的标题合并具有相同标题的多个CSV文件

转载 作者:行者123 更新时间:2023-12-03 10:47:48 28 4
gpt4 key购买 nike

我必须合并具有相同标题的多个CSV文件。
我必须保留第一个文件的 header ,并删除所有其他文件的 header ,然后合并它们并创建一个主文件。

文件1:

Id,city,name ,location
1,NA,JACK,CA

文件2:
ID,city,name,location
2,NY,JERRY,NY

输出:
Id,city,name,location
1,NA,JACK,CA
2,NY,JERRY,NY

目前,我正在使用此代码:
ls *.csv | xargs -n 1 tail -n+2 > master.csv

这段代码将完美地合并文件,但是由于我需要第一个文件的 header ,所以不会给我 header 。

我该怎么办?

最佳答案

awk 'FNR==1 && NR!=1{next;}{print}' *.csv

在solaris Unix上测试:
> cat file1.csv
Id,city,name ,location
1,NA,JACK,CA
>
> cat file2.csv
ID,city,name,location
2,NY,JERRY,NY
>
> nawk 'FNR==1 && NR!=1{next;}{print}' *.csv
Id,city,name ,location
1,NA,JACK,CA
2,NY,JERRY,NY
>

kevin-d给出的解释:

FNR is the number of lines (records) read so far in the current file. NR is the number of lines read overall. So the condition 'FNR==1 && NR!=1{next;}' says, "Skip this line if it's the first line of the current file, and at least 1 line has been read overall." This has the effect of printing the CSV header of the first file while skipping it in the rest.



Link了解 之间的区别

关于unix - Unix:通过保留第一个文件的标题合并具有相同标题的多个CSV文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16890582/

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