【问题标题】:Awk script, counting the number of +value and -valueawk脚本,统计+value和-value的个数
【发布时间】:2021-06-14 11:15:18
【问题描述】:

在以下列表中是 Benzin 每天的价格,我想要每天与前一天的差异(第一天不会出现在输出中)

  • 语句末尾:价格上涨的天数, 保持不变或不可用。
list of benzin prise
01.05.2021 156
02.05.2021 154
03.05.2021 151
04.05.2021 152
05.05.2021 148
06.05.2021 149
07.05.2021 147
08.05.2021 150
09.05.2021 150
10.05.2021 152
11.05.2021 157
12.05.2021 151
13.05.2021 147
14.05.2021 144
15.05.2021 150

输出应该是这样的:

•   02.05.2021: -2
•   03.05.2021: -3
•   04.05.2021: 1
•   05.05.2021: -4
•   06.05.2021: 1
•   07.05.2021: -2
•   08.05.2021: 3
•   09.05.2021: 0
•   10.05.2021: 2
•   11.05.2021: 5
•   12.05.2021: -6
•   13.05.2021: -4
•   14.05.2021: -3
•   15.05.2021: 6
•   
•   Number increased: 6
•   Number missing or equal: 8

我尝试了这段代码,但仍然有一些不完善的地方,我正在处理它:

awk 'NR>2 {print $1 " " $2-p} {p=$2}'

我还需要统计增加和不增加的数字。

【问题讨论】:

    标签: linux awk


    【解决方案1】:

    仅使用您展示的示例,请尝试以下操作。

    awk '
    FNR>1{
      diff=($2-prevVal)
      if(diff>0){ increase++ }
      else      { missing++  }
      print $1": "diff
    }
    {
      prevVal=$2
    }
    END{
      print "Number increased: "increase+0 ORS "Number missing or equal: " missing+0
    }
    '  Input_file
    

    说明:为上述添加详细说明。

    awk '                         ##Starting awk program from here.
    FNR>1{                        ##If line is not first line then do following.
      diff=($2-prevVal)           ##Taking difference of 2nd column and prevVal here.
      if(diff>0){ increase++ }    ##If diff is greater than 0 then increase variable with 1
      else      { missing++  }    ##Else increase missing with 1 here.
      print $1": "diff            ##Printing 1st column with diff here.
    }
    {
      prevVal=$2                  ##Setting prevVal to 2nd column value here.
    }
    END{                          ##Starting END block of this program from here.
                                  ##Printing number of increased or missing/decreased values.
      print "Number increased: "increase+0 ORS "Number missing or equal: " missing+0
    }
    '  Input_file                 ##Mentioning Input_file name here. 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-25
      • 2016-02-27
      • 2012-08-12
      • 1970-01-01
      • 2012-03-05
      • 1970-01-01
      • 2012-06-26
      相关资源
      最近更新 更多