From: Ross Bamford Date: 2006-01-05T02:27:59+09:00 Subject: Re: Searching a file for keywords? On Wed, 04 Jan 2006 15:55:18 -0000, Steve Starr wrote: > I am trying to find out how to search a file and find certain key words > then print them. > > Example: > > #!/usr/bin/ruby > > system("cat /proc/partitions > drives.txt") > > > Output: > 8 0 1007616 sda > 8 1 1007600 sda1 > 3 0 33027622 hda > 3 1 14651248 hda1 > 3 2 14651280 hda2 > 3 3 3719047 hda3 > > Now i would just want to print the word hda to the screen. > > Any help would be nice. > Thanks > Maybe: File.open('/proc/partitions') do |f| f.each_line do |s| puts s if s =~ /hda/ # Or do you mean: # s.scan(/hda/) { |it| puts it } # ? end end Or: File.open('/proc/partitions') do |f| puts f.grep(/hda/) end Alternatively, here's a use for that wierd gets behaviour people are talking about, and those hateful Perl-type shortcuts: $ ruby -ne 'print if ~/hda/' /proc/partitions (effectively same as) $ ruby -e 'while gets; print if ~/hda/; end' /proc/partitions (I assume you already know about the tools that are provided for this outside Ruby). -- Ross Bamford - rosco@roscopeco.remove.co.uk