简体   繁体   English

使用awk或bash减去两列的值

[英]subtract the values of two columns using awk or bash

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. 我想减去第2列和第4列的值,并需要为输出创建一个新列。

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). 注意:您可以将awk命令全部放在一行上,但这样更整洁(如果需要,还可以更透明,更容易修改)。

This so.awk script: 这个so.awk脚本:

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: 给定文件data.txt的数据,发出以下命令:

 awk -f so.awk data.txt

(You may have to adjust the formatting to fit your exact needs) (您可能需要调整格式以满足您的确切需求)

This one-liner works: 这个单线工程:

awk 'NR == 1 { $5 = "diff." } NR >= 3 { $5 = $2 - $4 } 1' <input.txt

It 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

If you want to separate fields by tabs, this is wat you want: 如果你想按标签分隔字段,这是你想要的wat:

awk 'BEGIN { OFS = "\t" } NR == 1 { $5 = "diff." } NR >= 3 { $5 = $2 - $4 } 1' <input.txt

The one-liner by Taku Miyakawa can be simplified if you don't have a header: 如果您没有标题,可以简化Taku Miyakawa的单行:

awk '{ $5 = $2 - $4 } 1' input.txt > inputdiff.txt

Or with tab separation: 或者使用制表符分隔:

awk 'BEGIN { OFS = "\t" } { $5 = $2 - $4 } 1' input.txt > inputdiff.txt

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

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