使用 awk 或 bash 减去两列的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12005080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 22:33:08  来源:igfitidea点击:

subtract the values of two columns using awk or bash

bashawk

提问by user1606717

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

回答by Levon

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.awkscript:

这个so.awk脚本:

NR==1{print 
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
, " diff.\n"} NR>2{printf("%s\t%5.1f\n",
 awk -f so.awk data.txt
, -)}

gives:

给出:

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

Given your data in file data.txtissue this command:

鉴于您在文件中的数据data.txt发出此命令:

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

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

(您可能需要调整格式以满足您的确切需求)

回答by Taku Miyakawa

This one-liner works:

这个单行作品:

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

It gives:

它给:

awk '{  =  -  } 1' input.txt > inputdiff.txt

If you want to separate fields by tabs, this is wat you want:

如果您想按制表符分隔字段,这就是您想要的:

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

回答by Peter van Galen

The one-liner by Taku Miyakawa can be simplified if you don't have a header:

如果您没有标题,可以简化 Taku Miyakawa 的 one-liner:

##代码##

Or with tab separation:

或者使用制表符分隔:

##代码##