On Thu, Sep 28, 2006 at 02:30:37PM -0300, Luis A. Florit wrote:
> Pals: I want to evaluate a block selection with formulas to its value.
> So, if you have 2 lines like:
> 
> home roof 89.4 + 76 home roof
> home roof 17 + 13.3 home roof
> 
> I would like to replace "89.4 + 76" by 165.4 and "17 + 13.3" by 30.3
> by selecting the block with the formulas and applying some command
> sequence (for example, using perl, bc, python, etc).
> Of course, I want this for arbitrary aritmetic formulas.
> 
>     Thanks!
> 
>         Luis.

     On Linux, I can use the bc command like this:

:s/\d[0-9 .+*/-]*/\=substitute(system('echo ' . submatch(0) . ' | bc'), '\n', 
'', 'g')

That is,

:s/<pat>/\=<expr>

where my pattern <pat> is '\d[0-9 .+*/-]*', a first attempt at capturing
the sort of "arithmetic string" you have in mind.  Inside <expr>,
submatch(0) is replaced by the matched text, such as "89.4 + 76".  Then

        system('echo 89.4 + 76 | bc')

will pass the string to bc as stdin and return the result.  I wrapped
this in substitute() to strip off the trailing newline character.

     It will be easier to read and maintain if you do something like
this (untested):

fun! EvalMath(str)
  let res = system('echo ' . a:str . ' | bc')
  return substitute(res, '\n', '', 'g')
endfun

:s/\d[0-9 .+*/-]*/\=EvalMath(submatch(0))

HTH                                     --Benji Fisher

Reply via email to