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

7 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

Karan Bohra said...

< epoch.txt \
sed -e '
1bhd
G;h;s/\n/ - /p
g;s/\n.*//
:hd
h;d
' |
while IFS= read -r Line; do
result=$(echo "$Line" | bc -l)
printf '%s = %d\n' "$Line" "$result"
done

Karan Bohra said...

set --
while read num; do set -- ${num:+"$num"} ${1+"$@"}; done < epoch.txt
dc -e "
[ - ]s1
[ = ]s2
[rddnl1nscrdnl2n-pszlc]sA
[z2!>Az2!>B]sB
$*
lBx
"

Karan Bohra said...
This comment has been removed by the author.
Karan Bohra said...



if='epoch.txt'

< $if sed '/^[-+]\{0,1\}[1-9][0-9]*$/!d;s/-/_/' |
dc -e "
[q]sq
[lPn[ - ]nlpn[ = ]n]sd
[?z0=qdsPlp-ldxplPspclbx]sb
?splbx
"

© Jadu Saikia www.UNIXCL.com