From: Chris Date: 2002-04-16T05:42:46+09:00 Subject: Re: need help on using Ruby to replace some SED expressions In article <90250227.0204151017.1503fb89@posting.google.com>, kackson@yahoo.com (kackson) wrote: > I tried sed. But it is getting really tough when I keep realizing I've > things to expand and expand and expand into a huge chunk of regular > expressions that now become completely unreadable and hard to > maintain. > So, as a beginner of Ruby, any advise on the question below is > apprecaited. > > I need to: > 1. read an input file > 2. For everyline, if the FIRST word has a dot '.', replace it with $. > Note, the first word may/maynot have been indented. > 3. For the rest of the line, replace all occurance of '@' with '^'. > 4. If there is something like '(2 + 3)' somewhere along the line, > evaluate it and replace the entire expression i.e. (2 + 3) with the > result, i.e. 5. Note, the brackets are gone. And it could be +, *, -, > or divide. If it is even possible for mathmatical routines such as > log/sin, etc. That would be even better. This seems like it should work, but hangs when I try to run it... #!/usr/local/bin/ruby class String def eval_math! while self =~ /(log|sin|cos|tan)\s+(\d+)/ sub! $&, eval("Math.#{$1} #{$2}").to_s end re = /\(\s*[\-+]?\d+(\.\d+)?(\s*[+-\/*]\s*[\-+]?\d+(\.\d+)?)*\s*\)/ while self =~ re x = $& sub! x, eval(x).to_s end self end end ARGV.each do |filename| file = open(filename, "r") text = file.readlines file.close text.collect! do |line| line.sub!(/^(\s*\S*)\.(\S*)/, "#{$1}$#{$2}") line.sub!("@", "^") line.eval_math! end file = open(filename, "w") file.write(text.join) file.close end