From: Phrogz Date: 2009-11-22T13:46:19+09:00 Subject: Re: How to match and count On Nov 21, 8:00 pm, Ruby Newbee wrote: > 2009/11/22 Phrogz : > > On Nov 21, 7:09 pm, Ruby Newbee wrote: > >> awk '{if ($4~/something/) {i+=1}} END {print i}'  file.txt > >> That means if a line's 4th field match "something" then increase the > >> counter by 1. > >> How to write the corresponding ruby code? > > What is a 'field'? Whitespace delimited? > Yes, thanks. Here are two ways: # Don't read the whole file into memory, but do it one line at a time i = 0 file = File.open( "foo.txt" ) file.each_line do |line| pieces = line.split( /\s+/ ) i += 1 if pieces[ 3 ] =~ /something/ end # Just read the whole file at once, assuming it's small enough, # and create an array of the fourth column's col = File.read("foo.txt").scan(/.+/).map{ |line| line.scan(/\S+/) [3] } i = col.count{ |val| val =~ /something/ }