regex - Match pattern in a file ruby -
i want search string in file (mostly .txt file) , return true
if there match. i've tried multiple solutions such follows:
# 1. file.foreach('c:\installlist.txt').grep /java/ # 2. file.open("c:/installlist.txt") |f| f.each_line |line| if line =~ '/java/' puts "found java: #{line}" else puts "not found" end end end
but none of these seem work. please seems trivial thing, still not happening.
# 3. file.each_line('c:/installlist.txt') |li| puts li if (li[/java/]) end
here snippet of installlist.txt file.
swmsm 12.0.0.1
microsoft office live meeting 2007 8.0.6362.190
microsoft .net framework 4.5 4.5.50709
google update helper 1.3.24.15
vagrant 1.6.1
windows azure storage tools - v2.2.2 2.2.2.0
microsoft visual c++ 2005 redistributable 8.0.61001
aws command line interface 1.3.17
microsoft visual c++ 2008 redistributable - x86 9.0.30729.4148 9.0.30729.4148
microsoft silverlight 5.1.30214.0
oracle vm virtualbox 4.3.10 4.3.10
java auto updater 2.1.9.5
rapidboot shield 1.23
you read entire file string:
if file.read('file.txt') =~ /java/ # ... end
or process line line:
if file.foreach('file.txt').any? { |line| line =~ /java/ } # ... end
in case you're dealing file encoding other ascii / utf-8, have specify when opening file. open utf-16 file bom you'd use:
file.read('file.txt', mode: 'r:bom|utf-16:utf-8')
Comments
Post a Comment