I have a file containing one column of number:
1
2
4
4
10
I would like to calculate the difference between each number using awk. The output should be like this :
1
2
0
6
How can I do it ?
Just to make it shorter ...
% awk 'NR>1{print $1-p} {p=$1}' file
1
2
0
6
Try the following code :
awk '
NR == 1{old = $1; next} # if 1st line
{print $1 - old; old = $1} # else...
' file.txt
1
2
0
6
In case awk is not a strict requirement, a shell solution:
set -- $(< file)
p=$1; shift; while (($# > 0)); do echo $(($1 - p)); p=$1; shift; done
DRYer
set -- $(< file)
while (($#>0)); do [[ -n $p ]] && echo $(($1-p)); p=$1; shift; done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With