Wednesday, August 12, 2009

Bash script for sequential subtraction of numbers


Input file epoch.txt contains UNIX epoch time in the following format.

$ cat epoch.txt
1249887102
1249887121
1249887181
1249887241
1249887433
1249887481
1249887541
1249887601
1249887661

Required:
Subtract 1st number from 2nd number(i.e. 2nd-1st),3rd number minus 2nd number and so on ...

The bash script:

#!/bin/sh

FILE=epoch.txt
N=1
total=$(sed -n '$=' $FILE)
until [ "$N" -eq $total ]
do
S1=$N
((S2=N+1))
N=$S2
VAL1=$(sed -n "$S1 p" $FILE)
VAL2=$(sed -n "$S2 p" $FILE)
echo "$VAL2 - $VAL1 = $((VAL2 - VAL1))"
done




$ sh difcal.sh
1249887121 - 1249887102 = 19
1249887181 - 1249887121 = 60
1249887241 - 1249887181 = 60
1249887433 - 1249887241 = 192
1249887481 - 1249887433 = 48
1249887541 - 1249887481 = 60
1249887601 - 1249887541 = 60
1249887661 - 1249887601 = 60

3 comments:

Mahesh Kharvi said...

My awk version :)

awk 'NR==FNR{a[NR]=$1;count+=1;next} NR > count+1 {printf("%s - %s = %s\n",$1,a[NR-count-1],$1-a[NR-count-1])}' epoch.txt epoch.txt

Jadu Saikia said...

@Mahesh, thats a good awk solution. Thanks.

Jadu Saikia said...

Another way:

$ sed -e 's/[0-9]*/&\n&/' epoch.txt | sed -e '1d' -e '$d' | tac | paste -sd"- " | tr ' ' '\n'|tac | bc

19
60
60
192
48
60
60
60

© Jadu Saikia www.UNIXCL.com