0

I'm trying to filter/append lines of hex data from a large log-file, using Ruby and RegEx.

The lines of the log-file that I need look like this:

Data: 10 55 61 (+ lots more hex data)

I want to add all of the hex data, for further processing later. The regex /^\sData:(.+)/ should do the trick.

My Ruby-program looks like this:

puts "Start"

fileIn = File.read("inputfile.txt")

fileOut = File.new("outputfile.txt", "w+")
fileOut.puts "Start of regex data\n"    

fileIn.each_line do
    dataLine = fileIn.match(/^\sData:(.+)/).captures    
    fileOut.write dataLine
end

fileOut.puts "\nEOF"
fileOut.close

puts "End"

It works - sort of - but the lines in the output file are all the same, just repeating the result of the first regex match.

What am I doing wrong?

1 Answer 1

2

You are iterating over the same entire file. You need to iterate over the line.

fileIn.each_line do |line|
    dataLine = line.match(/^\sData:(.+)/).captures    
    fileOut.write dataLine
end
Sign up to request clarification or add additional context in comments.

3 Comments

Good point! But now I get an error: <code> Start sma_data.rb:20:in block in <main>': undefined method captures' for nil:NilClass (NoMethodError) from sma_data.rb:19:in each_line' from sma_data.rb:19:in <main>' </code>
That means you have a line that does not match that regex. You need to apply captures only then dataLine is not nil.
I thought this might do: fileIn.each_line do |line| line =~ /^\sData:(.+)/ if($1) fileOut.write $1 end end but I get this error: sma_regex.rb:12:in block in <main>': invalid byte sequence in UTF-8 (ArgumentError) from sma_regex.rb:8:in each_line' from sma_regex.rb:8:in `<main>' PS: Can't seem to get code formatting to work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.