unix awk if语句与简单的数学

9jyewag0  于 2023-10-18  发布在  Unix
关注(0)|答案(5)|浏览(160)

我只是想在CSV文件上做一些基本的计算。
数据类型:

31590,Foo,70
28327,Bar,291
25155,Baz,583
24179,Food,694
28670,Spaz,67
22190,bawk,4431
29584,alfred,142
27698,brian,379
24372,peter,22
25064,weinberger,8

下面是我的简单awk脚本:

#!/usr/local/bin/gawk -f
BEGIN { FPAT="([^,]*)|(\"[^\"]+\")"; OFS=","; OFMT="%.2f"; }
    NR > 1
END { if ($3>1336) $4=$3*0.03; if ($3<1336) $4=$3*0.05;}1**

输出错误:

31590,Foo,70
28327,Bar,291
28327,Bar,291
25155,Baz,583
25155,Baz,583
24179,Food,694
24179,Food,694
28670,Spaz,67
28670,Spaz,67
22190,bawk,4431
22190,bawk,4431
29584,alfred,142
29584,alfred,142
27698,brian,379
27698,brian,379
24372,peter,22
24372,peter,22
25064,weinberger,8
25064,weinberger,8

异常输出:

31590,Foo,70,3.5
28327,Bar,291,14.55
25155,Baz,583,29.15
24179,Food,694,34.7
28670,Spaz,67,3.35
22190,bawk,4431,132.93
29584,alfred,142,7.1
27698,brian,379,18.95
24372,peter,22,1.1
25064,weinberger,8,.04

简单的数学运算是,如果字段$3 > 1336 = $3*.03,则结果为字段$4字段$3 < 1336 = $3*.05,则结果为字段$4

13z8s7eq

13z8s7eq1#

不需要强制awk重新编译每一条记录(通过赋值为$4),只需打印当前记录,然后输出计算结果:

awk 'BEGIN{FS=OFS=","; OFMT="%.2f"} {print $0, $3*($3>1336?0.03:0.05)}' file
dphi5xsq

dphi5xsq2#

在END块中不应该有任何内容

BEGIN {
    FS = OFS = ","
    OFMT="%.2f"
}
{
    if ($3 > 1336) 
        $4 = $3 * 0.03
    else 
        $4 = $3 * 0.05        
    print
}

这导致

31590,Foo,70,3.5
28327,Bar,291,14.55
25155,Baz,583,29.15
24179,Food,694,34.7
28670,Spaz,67,3.35
22190,bawk,4431,132.93
29584,alfred,142,7.1
27698,brian,379,18.95
24372,peter,22,1.1
25064,weinberger,8,0.4
wswtfjt7

wswtfjt73#

$ awk -F, -v OFS=, '{if ($3>1336) $4=$3*0.03; else $4=$3*0.05;} 1' data
31590,Foo,70,3.5
28327,Bar,291,14.55
25155,Baz,583,29.15
24179,Food,694,34.7
28670,Spaz,67,3.35
22190,bawk,4431,132.93
29584,alfred,142,7.1
27698,brian,379,18.95
24372,peter,22,1.1
25064,weinberger,8,0.4

讨论
END块不是在每一行的末尾执行,而是在整个文件的末尾执行。因此,它在这里没有帮助。
原始代码有两个独立的条件,NR>11。每一个的默认操作都是打印该行。这就是为什么在“错误输出”中,第一行之后的所有行都在输出中加倍。

zxlwwiss

zxlwwiss4#

awk

awk -F, -v OFS=, '$3>1336?$4=$3*.03:$4=$3*.05' file

conditional-expression ? action1 : action2 ;是awk中更短的三进制运算符。

i7uq4tfw

i7uq4tfw5#

mawk '$4 = (2 * ((_ = .01 * $3) < 13.36) + 3)*_' FS=, OFS=,
31590,Foo,70,3.5
28327,Bar,291,14.55
25155,Baz,583,29.15
24179,Food,694,34.7
28670,Spaz,67,3.35
22190,bawk,4431,132.93
29584,alfred,142,7.1
27698,brian,379,18.95
24372,peter,22,1.1
25064,weinberger,8,0.4

相关问题