I have a file that contains some numbers
$ cat file.dat
0.092593
0.048631
0.027957
0.030699
0.026250
0.038156
0.011823
0.013284
0.024529
0.022498
0.013217
0.007105
0.018916
0.014079
I want to make a new file that contains the difference of the current line with the previous line. Expected output should be
$ cat newfile.dat
-0.043962
-0.020674
0.002742
-0.004449
0.011906
-0.026333
0.001461
0.011245
-0.002031
-0.009281
-0.006112
0.011811
-0.004837
Thinking this was trivial, I started with this piece of code
f="myfile.dat"
while read line; do
curr=$line
prev=
bc <<< "$line - $prev" >> newfile.dat
done < $f
but I realized quickly that I have no idea how to access the previous line in the file. I guess I also need to account for that no subtraction should take place when reading the first line. Any guidance on how to proceed is appreciated!
prev
is the value on the previous line. For the first line, the first block is not executed (due to theNR > 1
condition), soprev
only gets the value of the first line (and nothing else happens). For the second line, the difference between the second and first line is printed beforeprev
is set to the value of the second line. The blocks are executed in order, and for each line. – Kusalananda Sep 19 '18 at 14:42prev
is the value on the current line only at the very end of processing that line, before continuing with the next line. When we actually useprev
, it is the value of the previous line. – Kusalananda Sep 19 '18 at 14:57