如何基于标题名称添加两列并将结果粘贴到基于标题名称的第三行中? [英] How to add two columns based on header names and paste results in a third row based on header name?

查看:121
本文介绍了如何基于标题名称添加两列并将结果粘贴到基于标题名称的第三行中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何添加2列(测试1和测试2)并根据列标题名称将结果打印在第四列中? (CSV文件)-逗号分隔的文件

How can I add 2 columns (test 1 and test 2) and print the result in a fourth column based on column header names? (CSV file)- comma demilited file

输入:

test1 test2 test3 test4
1 2 x 
2 4 Y 

输出:

test1 test2 test3 test4
1 2 x 3
2 4 Y 6

我尝试了下面的方法,但是我希望它基于列标题而不是位置.

I tried the below which works but I want it to be based on the column headers and not positions.

awk -F, '{$3=$1+$2;} {print $1,$2,$3}' OFS=, testing.csv

awk -F, '{$3=$1+$2;} {print $1,$2,$3}' OFS=, testing.csv

输入:

test1 test2 test3 test4
1 2 x 
2 4 Y 

输出:

test1 test2 test3 test4 
1 2 x 3
2 4 Y 6

推荐答案

处理此问题的最佳方法是创建一个数组,该数组在读取标题行时将列标题字符串(即字段名称)映射到字段编号然后从此开始按其名称访问字段:

The best way to deal with this is to create an array that maps the column header strings (i.e. the field names) to the field numbers when reading the header line and then just access the fields by their names from then on:

$ awk '
    NR==1 { for (i=1;i<=NF;i++) f[$i]=i }
    NR>1 { $(f["test4"]) = $(f["test1"]) + $(f["test2"]) }
1' file
test1 test2 test3 test4
1 2 x 3
2 4 Y 6

我在上面假设您在输入中的数据行之间确实没有空白行.如果愿意的话,可以轻松处理.

I assumed above that you don't really have blank lines between data lines in your input. Trivially handled if you do.

如果您的输入/输出实际上是CSV,则只需创建一个BEGIN部分,声明:

If your input/output is really CSV then just create a BEGIN section declaring that:

$ cat file
test1,test2,test3,test4
1,2,x,
2,4,Y

$ awk 'BEGIN{FS=OFS=","} NR==1{for (i=1;i<=NF;i++) f[$i]=i} NR>1{$(f["test4"]) = $(f["test1"]) + $(f["test2"])} 1' file
test1,test2,test3,test4
1,2,x,3
2,4,Y,6

这篇关于如何基于标题名称添加两列并将结果粘贴到基于标题名称的第三行中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆