Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get numbers from a list in a file, output to another file in Ruby?

Tags:

ruby

I have a big text file that contains - among others- lines like these:

"X" : "452345230"

I want to find all lines that contain "X" , and take just the number (without the quotation marks), and then output the numbers in another file, in this fashion:

452349532

234523452

213412411

219456433

etc.

What I did so far is this:

myfile = File.open("myfile.txt")
x = [] 
myfile.grep(/"X"/) {|line|
   x << line.match( /"(\d{9})/ ).values_at( 1 )[0]
   puts x
   File.open("output.txt", 'w') {|f| f.write(x) }
}

it works, but the list it produces is of this form:

["23419230", "2349345234" , ... ]

How do I output it like I showed before, just numbers and each number in a line?

Thanks.

like image 311
KuanYin Avatar asked Feb 01 '26 22:02

KuanYin


1 Answers

Here's a solution that doesn't leave files open:

File.open("output.txt", 'w') do |output|
    File.open("myfile.txt").each do |line|
        output.puts line[/\d{9}/] if line[/"X"/]
    end
end
like image 61
pguardiario Avatar answered Feb 04 '26 15:02

pguardiario



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!