减去两列用awk或bash值 [英] subtract the values of two columns using awk or bash

查看:171
本文介绍了减去两列用awk或bash值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些文本文件,如下所示。我想减去柱2和4的值,并需要创建一个新的列向输出

  CO1 CO2 CO3 CO4R1 15.2 13.0 21.4
R2 23 15 15.7
R3 14 8 12

所需的输出

  CO1 CO2 CO3 CO4差异。R1 15.2 13.0 21.4 -6.2
R2 23 15 15.7 7.3
R3 14 8 12 2


解决方案

请注意:你可以把awk的命令都在一行,但这是整洁(加上更透明,更容易修改如果需要的话)。

so.awk 脚本:

  NR == 1 {$打印0差异。\\ n}
NR大于2 {printf的(%S \\ T%5.1f \\ n,$ 0 $ 2- $ 4)}

给出了:

  CO1 CO2 CO3 CO4差异。R1 15.2 13.0 21.4 -6.2
R2 23 15 15.7 7.3
R3 14 8 12 2.0

由于在文件中的数据的data.txt 发出以下命令:

 的awk -f so.awk的data.txt

(您可能需要调整的格式,以适应您的需求)

I have some text files as shown below. I would like to subtract the values of column 2 and 4 and need to create a new column to the output.

co1  co2   co3    co4

r1  15.2  13.0   21.4
r2  23    15     15.7
r3  14    8      12

desired output

co1  co2   co3   co4   diff.    

r1  15.2  13.0   21.4   -6.2
r2  23    15     15.7   7.3
r3  14    8      12     2

解决方案

Note: You could put the awk commands all on one line, but this is tidier (plus more transparent and easier to modify if need be).

This so.awk script:

NR==1{print $0, "   diff.\n"}
NR>2{printf("%s\t%5.1f\n", $0, $2-$4)}

gives:

co1  co2   co3   co4     diff.

r1  15.2  13.0   21.4    -6.2
r2  23    15     15.7     7.3
r3  14    8      12       2.0

Given your data in file data.txt issue this command:

 awk -f so.awk data.txt

(You may have to adjust the formatting to fit your exact needs)

这篇关于减去两列用awk或bash值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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