Groups | Search | Server Info | Login | Register


Groups > comp.lang.awk > #175

Re: Can awk interpret algebraic fields?

From Poutounet <Poutou@net.com>
Newsgroups comp.lang.awk
Subject Re: Can awk interpret algebraic fields?
Date 2011-04-22 11:36 +0200
Organization Aioe.org NNTP Server
Message-ID <iori6b$bid$1@speranza.aioe.org> (permalink)
References <iok16f$j4e$1@speranza.aioe.org> <g7KdnX2B0M7sJjDQnZ2dnUVZ_qadnZ2d@speakeasy.net>

Show all headers | View raw


John DuBois wrote, On 19/04/2011 18:42:
> In article<iok16f$j4e$1@speranza.aioe.org>, Poutounet<Poutou@net.com>  wrote:
>> Hello,
>>
>> I have a file with algebraic expressions as fields. I would like awk to interpret them (i.e.,
>> compute the results with specific values for each of the variables the expression contains).
>>
>> I tried the following example (in a unix-like shell):
>> 	echo "5.*a" | awk -v a=2 '{print 0+$1}'
>> but I get "5" as a result because awk only retains "5." and considers the rest as non-number
>> characters (as far as I understand how it works).
>>
>> Is it possible to have awk compute the algebraic expression and return 10, which is what I expect?
>
> You could use this library:
>
> ftp://ftp.armory.com/pub/lib/awk/eval
>
> Example:
>
> echo "5.*a" | gawk -v a=2 -f eval --source '
> BEGIN {
>      params["a"] = a
> }
> {
>      print eval($0, params)
> }
> '
>
> This prints "10".
>
> If your awk doesn't support the use of both a file and command line as program
> source, you can include eval in the main program source.
>
> 	John

Thanks Kenny and John for your helpful answers.

In the meanwhile, I also tried to have awk write the expressions in an awk program, and then run awk 
again with that program, which gives something like this:
echo "5.*a" | awk -v a=2 'BEGIN{print "{a="a";"} {print " print "$0";"} END{print "}"}' > tmp.awk
echo "" | awk -f tmp.awk

The code is ugly, but it is efficient when expressions are much more complex than in this example.

Cheers,
Poutounet

Back to comp.lang.awk | Previous | NextPrevious in thread | Next in thread | Find similar


Thread

Can awk interpret algebraic fields? Poutounet <Poutou@net.com> - 2011-04-19 15:03 +0200
  Re: Can awk interpret algebraic fields? gazelle@shell.xmission.com (Kenny McCormack) - 2011-04-19 13:39 +0000
  Re: Can awk interpret algebraic fields? spcecdt@armory.com (John DuBois) - 2011-04-19 11:42 -0500
    Re: Can awk interpret algebraic fields? Poutounet <Poutou@net.com> - 2011-04-22 11:36 +0200
      Re: Can awk interpret algebraic fields? Janis Papanagnou <janis_papanagnou@hotmail.com> - 2011-04-22 14:55 +0200

csiph-web