简体   繁体   中英

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

a,1
b,1
...

and another file2.csv with 2 columns looks like

a,24324
b,432

The first column is the same and sorted in file1.csv and 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:

a,24325
b,433

You can use the following 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 . next allows us to work with first file. 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. You can redirect the output to another file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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