Thursday, August 16, 2007

perl - modify numbers on each line

Recently had the expression

((a1 * b2 * c3) - (a1 * b3 * c2) - (a2 * b1 * c3) + (a3 * b1 * c2) + (a2 * b3 * c1) - (a3 * b2 * c1))

in which i needed to changed all a1, b2 etc to a[0], b[1] .. i.e to arrays and with subscripts starting from 0

the following did the trick
echo "the expression here" | perl -lpe 's/(\d)/$1-1/ge; s/(\d)/\[$1\]/g'

the two s/// are required cos first one with /ge the right hand side is evaluated as an expression and hence cannot put chars like '[' inside it