regex - sed - replace a variable of power N by the product of N variables -
from sed replace variable of power product of 2 variables, generalize "power 2" case "n power case".
the command line in "power 2" case :
sed 's/\([^(*+\/^-]*\(([^)]*)\)\?\)\^2/\1\*\1/g'
so
cos(2*a)^2+sin(3*b)^2+m1^2*m2^2*cos(4*c)
is replaced :
cos(2*a)*cos(2*a)+sin(3*b)*sin(3*b)+m1*m1*m2*m2*cos(4*c)
now, want transform :
cos(a)^3 +m1^4
to
cos(a)*cos(a)*cos(a)+m1*m1*m1*m1
is there way store exponent "n" , print n times variable powered with star symbol
?
it (we store exponent in pattern \2
) :
sed 's/\([^(*+\/^-]*\(([^)]*)\)\?\)\^\([0-9]*\)/
"print n times (pattern \2
) factors \1
"
\1\*\1*\1*\1 /g'
if somenone has solution other tools (other linux commands), take.
echo "cos(a)^3 +m1^4" | sed ' # encapsulate between + s/.*/+&+/ :a # each power object /\^/!b end # isolate power object h s#\(.*[-+/*^]\)\([^-+/*^]*\)^\([0-9]\{1,2\}\)\(.*\)#\1\ \2\ \4# # isolate power value convert in useable reproducing factor x s//00\3/ s/\(.\)\{0,1\}\(.\)\{0,1\}\(.\)\{0,1\}/\1c\2d\3/ s/0.//g;s/9/18/g;s/8/17/g;s/7/16/g;s/6/15/g;s/5/14/g;s/4/13/g;s/3/12/g;s/2/11/g;s/1/u/g :cdu s/1\(1*\)\([^1]\)/\2\1\2/g;t cdu s/c/dddddddddd/g;s/d/uuuuuuuuuu/g # dont replicate power 1 s/u// # got replication number # replicate g :repl s/^u\(u*\n.*\n\)\(.*\)\(\n\)\(.*\)/\1\2\3*\2\4/;t repl # reassemble s/\n//g b :end # remove + s/.\(.*\)./\1/ '
let's crazy in mad world (i don't recommend in production, maintenance , modification)
- limited power: positive, integer , smaller 999
- some comment in code not exhaustive (a bit long)
- tested on gnu sed posix compliant
- recursive process simple powered argument between
+-*/^
should work limit of sed itself.
Comments
Post a Comment