2 # from: @(#)math.sed 8.1 (Berkeley) 6/6/93
3 # $NetBSD: math.sed,v 1.3 1997/01/09 20:21:36 tls Exp $
5 # Addition and multiplication in sed.
6 # ++ for a limited time only do (expr) too!!!
8 # Kevin S Braunsdorf, PUCC UNIX Group, ksb@cc.purdue.edu.
11 # echo "4+7*3" | sed -f %f
13 # make sure the expression is well formed
17 poorly formed expression, operator on the end
22 poorly formed expression, leading operator
26 # fill hold space with done token
31 # main loop, process operators (*, + and () )
37 /^\(.*\)(\([^)]*\))\(.*\)$/{
41 s/^\(.*\)\n\(.*\)(\([^()]*\))\(.*\)$/()\2@\4@\1/
46 /^\([0-9]*\)\+\([0-9+*]*\*[0-9]*\)$/{
64 s/\(.*\)\n\([^@]*\)@\([^@]*\)@\(.*\)/\2\1\3/
66 s/[^@]*@[^@]*@\(.*\)/\1/
77 # turn mul into add until 1*x -> x
84 s/^\([0-9]*\)0\*\([0-9]*\)/\1*\20/
87 s/^\([0-9]*\)1\*/\10*/
88 s/^\([0-9]*\)2\*/\11*/
89 s/^\([0-9]*\)3\*/\12*/
90 s/^\([0-9]*\)4\*/\13*/
91 s/^\([0-9]*\)5\*/\14*/
92 s/^\([0-9]*\)6\*/\15*/
93 s/^\([0-9]*\)7\*/\16*/
94 s/^\([0-9]*\)8\*/\17*/
95 s/^\([0-9]*\)9\*/\18*/
96 s/\*\([0-9*]*\)/*\1+\1/
99 # get rid of a plus term until 0+x -> x
109 /^\([0-9]*\)\+\([0-9*+]*\)\+=/{
113 /^\([0-9]*\)0\+\([0-9]*\)\([0-9]\)=/{
117 /^\([0-9]*\)\([0-9]\)\+\([0-9]*\)0=/{
121 /^\([0-9]*\)0\+\([0-9*+]*\)\+\([0-9]*\)\([0-9]\)=/{
125 /^\([0-9]*\)\([0-9]\)\+\([0-9*+]*\)\+\([0-9]*\)0=/{
129 s/^\([0-9]*\)1\+/\10+/
130 s/^\([0-9]*\)2\+/\11+/
131 s/^\([0-9]*\)3\+/\12+/
132 s/^\([0-9]*\)4\+/\13+/
133 s/^\([0-9]*\)5\+/\14+/
134 s/^\([0-9]*\)6\+/\15+/
135 s/^\([0-9]*\)7\+/\16+/
136 s/^\([0-9]*\)8\+/\17+/
137 s/^\([0-9]*\)9\+/\18+/
139 s/9=\([0-9]*\)$/_=\1/
140 s/8=\([0-9]*\)$/9=\1/
141 s/7=\([0-9]*\)$/8=\1/
142 s/6=\([0-9]*\)$/7=\1/
143 s/5=\([0-9]*\)$/6=\1/
144 s/4=\([0-9]*\)$/5=\1/
145 s/3=\([0-9]*\)$/4=\1/
146 s/2=\([0-9]*\)$/3=\1/
147 s/1=\([0-9]*\)$/2=\1/