Saeid Herawi
Saeid Herawi

Reputation: 61

Awk script, counting the number of +value and -value

in fowlloing list are the prices Benzin everyday, i want for each day the difference to the previous day (the first day does not appear in the output)

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

the output should looks like this :

•   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

I tried this code but still ist some how not complate, im working on it:

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

i stil need to count the nummbers which increased and not increased.

Upvotes: 0

Views: 152

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133610

With your shown samples only, please try following.

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

Explanation: Adding detailed explanation for above.

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. 

Upvotes: 5

Related Questions