Hi,
I am writing a script to search for a particular string in a file and
then copy all lines starting from matching-line to another file.
Following should make it clear again:
* search for first occurrence of a particular string in a file
* find it's line number
* copy certain text in all lines or entire line, starting from above
line number to EOF to another file
I can find the matching line's number as:
<code>
File.foreach(afile) do |line|
if line =~ /(\S+:)(\S+:)(\S+:)8055:(\S+:)(\S+)/
puts "Found match at #{$.}"
lnumber = $.
end
end
</code>
But I am not sure how to copy range of line numbers to another file. I
thought about using another File open again and then use range operators
($. == lnumber) as mentioned here,
http://pleac.sourceforge.net/pleac_ruby/patternmatching.html , but
wondering if there is any other better way that I might be missing here.
Any suggestions?
thanks,
neuby.r
···
--
Posted via http://www.ruby-forum.com/.
Forget about line numbers, you are already iterating over the lines,
just iterate first until that line, then read the rest of the file and
write it out:
File.open(file) do |f|
File.open(output, "w") do |out|
line = f.gets until line =~ your_regex
out.puts line
out.write f.read
end
Jesus.
···
On Wed, Jul 20, 2011 at 7:18 AM, Neubyr Neubyr <neubyr@gmail.com> wrote:
Hi,
I am writing a script to search for a particular string in a file and
then copy all lines starting from matching-line to another file.
Following should make it clear again:
* search for first occurrence of a particular string in a file
* find it's line number
* copy certain text in all lines or entire line, starting from above
line number to EOF to another file
I can find the matching line's number as:
<code>
File.foreach(afile) do |line|
if line =~ /(\S+:)(\S+:)(\S+:)8055:(\S+:)(\S+)/
puts "Found match at #{$.}"
lnumber = $.
end
end
</code>
But I am not sure how to copy range of line numbers to another file. I
thought about using another File open again and then use range operators
($. == lnumber) as mentioned here,
Pattern Matching , but
wondering if there is any other better way that I might be missing here.
Any suggestions?
Neubyr Neubyr wrote in post #1011813:
I am writing a script to search for a particular string in a file and
then copy all lines starting from matching-line to another file.
Following should make it clear again:
* search for first occurrence of a particular string in a file
* find it's line number
* copy certain text in all lines or entire line, starting from above
line number to EOF to another file
$ sed -n -e '/rx/,$ {s/foo/bar/g; p}' a_file

Kind regards
robert
···
--
Posted via http://www.ruby-forum.com/\.