嗨,我有一个像这样的文件格式(TSV)
Name type Age Weight Height
Xxx M 12,34,23 50,30,60,70 4,5,6,5.5
Yxx F 21,14,32 40,50,20,40 3,4,5,5.5
我想将年龄、体重和身高中的所有值相加,并在其后添加一列,然后再添加一些百分比,比如总身高/总体重(awk'$0=$0“\t”(NR==1?“百分比”:$8/$7)”。我有大量的数据集,无法使用excel
像这样
Name type Age Weight Height Total_Age Total_Weight Total_Height Percentage
Xxx M 12,34,23 50,30,60,70 4,5,6,5.5 69 210 20.5 0.097
Yxx F 21,14,32 40,50,20,40 3,4,5,5.5 67 150 17.5 0.11
在每个Unix设备上的任何shell中使用任何awk,并且没有在每个记录中创建新字段(这是低效的,因为它会导致awk在每次更改字段时重新构建记录),也没有更新输入记录(这是低效的,因为它会导致awk在每次更改记录时将记录重新拆分为字段)并设计用于以任意顺序处理任意数量的值输入列:
为了展示上述方法的功能优势,假设您需要添加更多的值,如
ShoeSize
和/或重新排列列的顺序,例如:现在运行上述脚本,注意为每个原始列添加了
Total_
列,但仍然在末尾添加了相同的Percentage
列的高度/重量:对于所显示的示例,请尝试以下代码
或添加上述
awk
代码的略短版本:解释:简单的解释是,取第三、第四和第五列的总和,并将它们分配到行的最后一列。根据OP的要求,相应地添加列值,该列值具有最后一列和最后第二列的除法值。使用
column -t
使其在输出上看起来更好如果必须多次执行相同的操作,还可以使用函数对数组值求和(假设值是以逗号分隔的数字)
重用来自RavinderSingh13的部分答案,并向Ed Morton表示衷心感谢,花时间提供大量反馈以改进代码:
输出
相关问题 更多 >
编程相关推荐