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