Extract lines with regular expressions

M

Michael Dore

I am a newb trying to take a list of data in a text file and print out a
new list of lines that contain certain characters...
I am not too worried about the actual regex - I can figure that out -
but I cannot seem to get it to implement correctly.

I found the following online (http://www.fepus.net/ruby1line.txt)

# print only lines that match a regular expression (emulates 'grep')
$ ruby -pe 'next unless $_ =~ /regexp/' < file.txt

and it does exactly what I want, but...

how do I use this (or something similar, ie grep) in a .rb script?

I have tried this:
vl_stops.each do |vl_stops|
puts "#{vl_stops}"
search = Regexp.new("^\b(#{vl_stops}:)\w*")
files.each do |file|
f = File.open(directory+file)
f.grep(search)
puts #what goes here? line?
end
f.close
end
puts
end
based on something I found here
(http://www.rousette.org.uk/blog/archives/2004/10/21/gtd-using-text-files/)

But I am not sure how to seal the deal, as it were...
Any thoughts would be appreciated.
Thanks!
 
R

Robert Klemme

I am a newb trying to take a list of data in a text file and print out a
new list of lines that contain certain characters...
I am not too worried about the actual regex - I can figure that out -
but I cannot seem to get it to implement correctly.

I found the following online (http://www.fepus.net/ruby1line.txt)

# print only lines that match a regular expression (emulates 'grep')
$ ruby -pe 'next unless $_ =~ /regexp/' < file.txt

and it does exactly what I want, but...

how do I use this (or something similar, ie grep) in a .rb script?

I have tried this:
vl_stops.each do |vl_stops|
puts "#{vl_stops}"
search = Regexp.new("^\b(#{vl_stops}:)\w*")
files.each do |file|
f = File.open(directory+file)
f.grep(search)
puts #what goes here? line?
end
f.close
end
puts
end
based on something I found here
(http://www.rousette.org.uk/blog/archives/2004/10/21/gtd-using-text-files/)

But I am not sure how to seal the deal, as it were...
Any thoughts would be appreciated.
Thanks!

files.each do |file|
File.open(directory+file) do |f|
puts f.grep(search)
end

Or, for large files

files.each do |file|
File.open(directory+file) do |f|
f.each do |line|
puts line if search ~= line
end
end

Kind regards

robert
 
7

7stud --

Michael said:
I have tried this:

vl_stops.each do |vl_stops|

First, you might try dreaming up more than one variable name.

Second, if you are searching for simple strings, like 'hello', you can
do this:

search_string = 'hello'

IO.foreach("data.txt") do |line|
if line.include?(search_string)
puts line
end
end
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top