简体   繁体   English

如何使用awk在Ubuntu中添加2个csv文件的第二行的值?

[英]How to use awk to add the value of second lines of 2 csv files in Ubuntu?

I am using ubuntu and we got a csv file1.csv with 2 columns looks like 我正在使用ubuntu,我们有2列的csv file1.csv看起来像

a,1
b,1
...

and another file2.csv with 2 columns looks like 另一个有2列的file2.csv看起来像

a,24324
b,432

The first column is the same and sorted in file1.csv and file2.csv. 第一列是相同的,并在file1.csv和file2.csv中排序。 How to use awk to add the the value of second lines of 2 csv files in Ubuntu to get the result like this: 如何使用awk在Ubuntu中添加2个csv文件的第二行的值,以得到如下结果:

a,24325
b,433

You can use the following awk : 您可以使用以下awk

awk -F, -v OFS=, 'NR==FNR{a[$1]=$2;next}{$2+=a[$1]}1' file1.csv file2.csv
a,24325
b,433

We set the input and output field separator to , . 我们设置的输入和输出字段分隔符, Using NR==FNR construct, we load the file1.csv in to an array a . 使用NR==FNR构造,我们将file1.csv加载到数组a next allows us to work with first file. next ,我们可以处理第一个文件。 Once the file is loaded in memory, we move to the second file and just add the value from our array to second column. 一旦文件加载到内存中,我们将移至第二个文件,只需将数组中的值添加到第二列。

This will print the output to STDOUT. 这会将输出打印到STDOUT。 You can redirect the output to another file. 您可以将输出重定向到另一个文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM