Forum: Ruby Reading RTF + Text File and pattern matching

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Sukhwinder T. (Guest)
on 2009-01-12 15:27
Attachment: pattern_matching_solution.txt (0 Bytes)
Reading RTF and Text File in Ruby and Pattern Matching/searching from
file and replacing with your data.

if you want to read RTF of Text file then u can take help from this code
. Try out following  solution.

filename ='sukhitambar.rtf'
targetfilename ='princetambar.rtf', 'r') do |f|   # open file for reading
        lines = f.readlines       # read into array of lines
        lines.each do |line|      # traversing line by line
        line= line.gsub!(/<TodayDate>/,  # Pattern (
<TodayDate> )
         line= line.gsub!(/<......>/,data to be replaced), 'a') do |content|  # opening new
target file in append mode
          content.puts line               # saving the line to another
rtf file

In the above code user can read data from Rich Text Format (RTF) file
and search for some specific pattern and replace with his required
data.and saved it to another RTF file. i hope this code will help for
those whose want to read from RTF file and do pattern matching.


By :-

Sukhwinder Singh Tambar
Jarmo P. (Guest)
on 2009-01-13 23:41
Or, in little shorter way:

data = File.readlines("test1.txt") #read file into array! {|line| line.gsub(/world/, "ruby")} #invoke on each line gsub"test2.txt", "a") {|f| f.puts data} #output data to other file

Although I don't understand, why would you want to append instead of

Sukhwinder Tambar wrote:
> Reading RTF and Text File in Ruby and Pattern Matching/searching from
> file and replacing with your data....
Sukhwinder T. (Guest)
on 2009-01-15 08:17
Thanks Jarmo P. for the little way to do this. i am using append
mode bcz i have lot of Pattern need to be replace with my date
dynamically. so i open the file in append mode inside the loop.

One more thing. in text file gsub find the required pattern easily but
while reading from RTF file we get the data in other way. so i did this

line= line.gsub!(/<TodayDate>/,

i am agree with map you used.

bye the thank for shorter the code.
This topic is locked and can not be replied to.