1# 2# @(#)math.sed 8.1 (Berkeley) 06/06/93 3# 4# Addition and multiplication in sed. 5# ++ for a limited time only do (expr) too!!! 6# 7# Kevin S Braunsdorf, PUCC UNIX Group, ksb@cc.purdue.edu. 8# 9# Ex: 10# echo "4+7*3" | sed -f %f 11 12# make sure the expression is well formed 13s/[ ]//g 14/[+*\/-]$/{ 15 a\ 16 poorly formed expression, operator on the end 17 q 18} 19/^[+*\/]/{ 20 a\ 21 poorly formed expression, leading operator 22 q 23} 24 25# fill hold space with done token 26x 27s/^.*/done/ 28x 29 30# main loop, process operators (*, + and () ) 31: loop 32/^\+/{ 33 s/// 34 b loop 35} 36/^\(.*\)(\([^)]*\))\(.*\)$/{ 37 H 38 s//\2/ 39 x 40 s/^\(.*\)\n\(.*\)(\([^()]*\))\(.*\)$/()\2@\4@\1/ 41 x 42 b loop 43} 44/^[0-9]*\*/b mul 45/^\([0-9]*\)\+\([0-9+*]*\*[0-9]*\)$/{ 46 s//\2+\1/ 47 b loop 48} 49/^[0-9]*\+/{ 50 s/$/=/ 51 b add 52} 53x 54/^done$/{ 55 x 56 p 57 d 58} 59/^()/{ 60 s/// 61 x 62 G 63 s/\(.*\)\n\([^@]*\)@\([^@]*\)@\(.*\)/\2\1\3/ 64 x 65 s/[^@]*@[^@]*@\(.*\)/\1/ 66 x 67 b loop 68} 69i\ 70help, stack problem 71p 72x 73p 74q 75 76# turn mul into add until 1*x -> x 77: mul 78/^0*1\*/{ 79 s/// 80 b loop 81} 82/^\([0-9]*\)0\*/{ 83 s/^\([0-9]*\)0\*\([0-9]*\)/\1*\20/ 84 b mul 85} 86s/^\([0-9]*\)1\*/\10*/ 87s/^\([0-9]*\)2\*/\11*/ 88s/^\([0-9]*\)3\*/\12*/ 89s/^\([0-9]*\)4\*/\13*/ 90s/^\([0-9]*\)5\*/\14*/ 91s/^\([0-9]*\)6\*/\15*/ 92s/^\([0-9]*\)7\*/\16*/ 93s/^\([0-9]*\)8\*/\17*/ 94s/^\([0-9]*\)9\*/\18*/ 95s/\*\([0-9*]*\)/*\1+\1/ 96b mul 97 98# get rid of a plus term until 0+x -> x 99: add 100/^\+\([0-9+*]*\)=/{ 101 s//\1/ 102 b loop 103} 104/^\([0-9*]*\)\+=/{ 105 s//\1/ 106 b loop 107} 108/^\([0-9]*\)\+\([0-9*+]*\)\+=/{ 109 s//\2+\1/ 110 b loop 111} 112/^\([0-9]*\)0\+\([0-9]*\)\([0-9]\)=/{ 113 s//\1+\2=\3/ 114 b add 115} 116/^\([0-9]*\)\([0-9]\)\+\([0-9]*\)0=/{ 117 s//\1+\3=\2/ 118 b add 119} 120/^\([0-9]*\)0\+\([0-9*+]*\)\+\([0-9]*\)\([0-9]\)=/{ 121 s//\1+\2+\3=\4/ 122 b add 123} 124/^\([0-9]*\)\([0-9]\)\+\([0-9*+]*\)\+\([0-9]*\)0=/{ 125 s//\1+\3+\4=\2/ 126 b add 127} 128s/^\([0-9]*\)1\+/\10+/ 129s/^\([0-9]*\)2\+/\11+/ 130s/^\([0-9]*\)3\+/\12+/ 131s/^\([0-9]*\)4\+/\13+/ 132s/^\([0-9]*\)5\+/\14+/ 133s/^\([0-9]*\)6\+/\15+/ 134s/^\([0-9]*\)7\+/\16+/ 135s/^\([0-9]*\)8\+/\17+/ 136s/^\([0-9]*\)9\+/\18+/ 137 138s/9=\([0-9]*\)$/_=\1/ 139s/8=\([0-9]*\)$/9=\1/ 140s/7=\([0-9]*\)$/8=\1/ 141s/6=\([0-9]*\)$/7=\1/ 142s/5=\([0-9]*\)$/6=\1/ 143s/4=\([0-9]*\)$/5=\1/ 144s/3=\([0-9]*\)$/4=\1/ 145s/2=\([0-9]*\)$/3=\1/ 146s/1=\([0-9]*\)$/2=\1/ 147/_/{ 148 s//_0/ 149 : inc 150 s/9_/_0/ 151 s/8_/9/ 152 s/7_/8/ 153 s/6_/7/ 154 s/5_/6/ 155 s/4_/5/ 156 s/3_/4/ 157 s/2_/3/ 158 s/1_/2/ 159 s/0_/1/ 160 s/\+_/+1/ 161 /_/b inc 162} 163b add 164