I read about Dave Thomas Ruby one liners
Its says
  # print section of file between two regular expressions, /foo/ and /bar/
      $  ruby -ne '@found=true if $_ =~ /foo/; next unless @found; puts $_; exit if $_ =~ /bar/' < file.txt
May I know how i can use this is my Ruby code and not from command line?
According to ruby CLI reference,
-n              assume 'while gets(); ... end' loop around your script
-e 'command'    one line of script. Several -e's allowed. Omit [programfile]
So, just copy the code snippet to a ruby file enclosed in gets() loop
foobar.rb
while gets()
   @found=true if $_ =~ /foo/
   next unless @found
   puts $_
   exit if $_ =~ /bar/
end
And execute the file using
ruby foobar.rb < file.txt
You can also replace IO redirect by reading the file programmatically
file = File.new("file.txt", "r")
while (line = file.gets)
   @found=true if line =~ /foo/
   next unless @found
   puts line
   exit if line =~ /bar/
end
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With