Adarsh Parthasarathy
Adarsh Parthasarathy

Reputation: 11

Text insertion using Ruby

I have a .txt file with text laid out like this:

11/14/2015, 13:51: John Doe: Hi there
11/14/2015, 13:52: Jane Doe: Hi, my name is Jane.
Nice to meet you.
11/14/2015, 13:53: Joe Bloggs: Hey there everyone!
Shall we get started?

What I'd like to accomplish is to insert the "label", so to speak, of the previous message in front of a message that lacks a label. For example, the end result would look like this:

11/14/2015, 13:51: John Doe: Hi there
11/14/2015, 13:52: Jane Doe: Hi, my name is Jane.
11/14/2015, 13:52: Jane Doe: Nice to meet you.
11/14/2015, 13:53: Joe Bloggs: Hey there everyone!
11/14/2015, 13:53: Joe Bloggs: Shall we get started?

How would I go about doing this?

Upvotes: 0

Views: 50

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110685

txt =<<_
11/14/2015, 13:51: John Doe: Hi there
11/14/2015, 13:52: Jane Doe: Hi, my name is Jane.
Nice to meet you.
11/14/2015, 13:53: Joe Bloggs: Hey there everyone!
Shall we get started?
_

R = %r{\A\d{2}/\d{2}/\d{4}\,\s\d{2}:\d{2}:\s}

arr = txt.split("\n")
  #=> ["11/14/2015, 13:51: John Doe: Hi there",
  #    "11/14/2015, 13:52: Jane Doe: Hi, my name is Jane.",
  #    "Nice to meet you.",
  #    "11/14/2015, 13:53: Joe Bloggs: Hey there everyone!",
  #    "Shall we get started?"] 
(1..arr.size-1).each do |i|
  next if arr[i] =~ R
  previous_line = arr[i-1]
  leader = previous_line[0, 2 + previous_line.rindex(": ")]
  arr[i] = leader.concat(arr[i]) 
end
arr
  #=> ["11/14/2015, 13:51: John Doe: Hi there",
  #    "11/14/2015, 13:52: Jane Doe: Hi, my name is Jane.",
  #    "11/14/2015, 13:52: Jane Doe: Nice to meet you.",
  #    "11/14/2015, 13:53: Joe Bloggs: Hey there everyone!",
  #    "11/14/2015, 13:53: Joe Bloggs: Shall we get started?"] 

Upvotes: 1

sawa
sawa

Reputation: 168131

input = StringIO.new <<~_
  11/14/2015, 13:51: John Doe: Hi there
  11/14/2015, 13:52: Jane Doe: Hi, my name is Jane.
  Nice to meet you.
  11/14/2015, 13:53: Joe Bloggs: Hey there everyone!
  Shall we get started?
_

label = nil
output = input.each_with_object("") do
  |l, s|
  if l =~ %r[\A\d{2}/\d{2}/\d{4}, \d{2}:\d{2}: ]
    label = $&
    s.concat(l)
  else
    s.concat(label + l)
  end
end
puts output

output

11/14/2015, 13:51: John Doe: Hi there
11/14/2015, 13:52: Jane Doe: Hi, my name is Jane.
11/14/2015, 13:52: Nice to meet you.
11/14/2015, 13:53: Joe Bloggs: Hey there everyone!
11/14/2015, 13:53: Shall we get started?

Upvotes: 1

Related Questions