简体   繁体   English

用awk或sed在两列之间进行减法

[英]subtraction between two columns with awk or sed

I have some text files. 我有一些文本文件。 I need to do the subtraction between second and fourth columns in each file. 我需要在每个文件的第二和第四列之间进行减法。 The subtracted values should print to the original files as fifth column. 减去的值应作为第五列打印到原始文件中。 How can I do this with awk or sed? 如何使用awk或sed执行此操作?

HII 62.0    HII 35.1
MEE 21.3    MEE 21.3
GLL 42.3    GLL 18.5
ASS 105.9   ASS 105.9
RRG 65.6
GLL 48.3
SES 83.5    

Desired output

HII 62.0    HII 35.1   26.9
MEE 21.3    MEE 21.3    0
GLL 42.3    GLL 18.5   23.8
ASS 105.9   ASS 105.9   0
RRG 65.6
GLL 48.3
SES 83.5

If the third and fourth columns are blank, no need to subtract. 如果第三和第四列为空白,则无需减去。

awk 'NF == 2 { print }
     NF == 4 { print $0, $2 - $4 }'

That could all be fitted onto one line, but it clearer what it is doing when it is spread over two lines. 所有这些都可以放在一条线上,但是当它分布在两条线上时,它会更清楚地显示正在做什么。

If you want more control over the format, you can use printf() instead of just print . 如果要进一步控制格式,可以使用printf()而不是print

After sanitizing trailing spaces in the data, it produces: 清理数据中的尾随空格后,它会产生:

HII 62.0    HII 35.1 26.9
MEE 21.3    MEE 21.3 0
GLL 42.3    GLL 18.5 23.8
ASS 105.9   ASS 105.9 0
RRG 65.6
GLL 48.3
SES 83.5

这可能适合您(GNU sed和Bash):

sed -ri '/^\S+\s+(\S+)\s+\S+\s+(\S+)/s//echo "&\t$(echo \1-\2|bc)"/e' file

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

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