From: Paul Duncan Date: 2002-04-16T05:00:22+09:00 Subject: Re: need help on using Ruby to replace some SED expressions --4oF+6Ged69J0+4/e Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable * kackson (kackson@yahoo.com) 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. >=20 > 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 is almost what you need: ---- #!/usr/bin/ruby lines =3D [] math_re =3D /\(([()+\-*\/\d\s]{3,})\)/ result =3D 0 input_file =3D ARGV.shift or die 'missing arguments' File.open(input_file) { |f| f.each { |line|=20 line.sub!(/\./, '$') if line =3D~ /^\s*([\w\.]+)/ line.gsub! /\@/, '^' if matches =3D math_re.match(line) (1...matches.length).each { |i| begin eval "result =3D #{matches[i]}" # WARNING: possible security hole line.gsub! Regexp.new(Regexp.escape matches[i]), result.to_s rescue =3D>detail $STDERR.puts "Invalid math match: '#{matches[i]}'" end } end puts line } } ---- Test file and results: pabs@bobby:~/proj/blah> cat test.txt && echo '----' && ./blah.rb test.txt asdf.asdf # should replace the first . asdfasdfasdf (5+3) # should change 5+3 to 8 asdf.asdfsadf.afdafk.asdf # should only change the first dot @@@@@@@@@@@@@@@@@ # should change at symbol to caret ---- asdf$asdf # should replace the first . asdfasdfasdf (8) # should change 8 to 8 asdf$asdfsadf.afdafk.asdf # should only change the first dot ^^^^^^^^^^^^^^^^^ # should change at symbol to caret ---- > I'm running short of time to experiment all the powerful set of ruby > methods for now. I hope some ruby expert could help. Hope this helps... PS I'm sure the real ruby experts can come up with an even more elegant solution :) > Thank you!!! --=20 Paul Duncan pabs in #gah (OPN IRC) http://www.pablotron.org/ OpenPGP Key ID: 0x82C29562 --4oF+6Ged69J0+4/e Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE8uzFTzdlT34LClWIRAm9NAJ9Q1nvdlDMbThtT67NZbfkjL8vO0gCeNwbS xahfJQb6zmJ8Y40ptlwTdgs= =/xnq -----END PGP SIGNATURE----- --4oF+6Ged69J0+4/e--