views:

260

answers:

4

I want to edit the following text so that every line begins with Dealer:. This means no wrapping/line breaks. For lines starting with System, wrapping is fine.

What would a solution in ruby look like? Thanks

This is located in a .txt file

Dealer: 5 seconds left to act
Dealer: hitman2714 wins the pot (9)
Dealer: Hand #1684326626D
Dealer: Guitou699 has 5 seconds left to
act
Dealer: Guit¤u699 has timed out
Dealer: baj Hasan has 5 seconds left to
act
Dealer: baj Hasan has timed out
Dealer: hitman2714 has 5 seconds left
to act
Dealer: hitman2714 has timed out
System: The nightly $10,000 guarantee
will be starting in 20 minutes
Dealer: Dealer: Hand #1684326626D
Dealer: Perspextive posts the big
blind of 25

Desired output:

Dealer: 5 seconds left to act
Dealer: hitman2714 wins the pot (9)
Dealer: Hand #1684326626D
Dealer: Guitou699 has 5 seconds left to act
Dealer: Guit¤u699 has timed out
Dealer: baj Hasan has 5 seconds left to act
Dealer: baj Hasan has timed out
Dealer: hitman2714 has 5 seconds left to act
Dealer: hitman2714 has timed out
System: The nightly $10,000 guarantee
will be starting in 20 minutes
Dealer: Dealer: Hand #1684326626D
Dealer: Perspextive posts the big blind of 25

+1  A: 
previous = ''

ARGF.each_with_index do |line, i|
  line.chomp!
  unless i == 0
    if line =~ /^Dealer/ || line =~ /^System/
      puts previous
      previous = line
    else
      previous << (previous =~ /^System/ ? "\n" : " ") << line
    end
  else
    previous = line
  end
end
puts previous

Uses STDIN and STDOUT for input and output.

Mladen Jablanović
+2  A: 
remove_newline = false

ARGF.each_line do |line|
    if line =~ /^(Dealer|System): /
        puts if remove_newline
        remove_newline = ($1 == 'Dealer')
    end
    line.sub!(/\n/, ' ') if remove_newline
    print line
end

If you don't mind eliminating the wrapping on the "System" lines, and if the file is small enough, you can do something like this:

puts ARGF.readlines.join('').gsub(/\n(?!Dealer: |System: )/, ' ')
FM
A: 

grep

Why use ruby if this kind of tool already exists

cat oldfile | grep ^Dealer: > newfile

ruby

If this is supposed to be part of a bigger ruby application, then there is nothing wrong with doing it in ruby.

content= File.read(oldfile)
content= content.grep(/^Dealer:/)
File.open(newfile, "w") { |f| f.write(content) }
johannes
A: 

content.gsub(/^(.*)\n(?!(Dealer|System|\Z))/, '\1 ')

Wayne Conrad