tags:

views:

30

answers:

2

I have the following string in a file called mib.txt:

[name=1.3.6.1.2.1.1.5.0, value=myrouter.ad.local (OCTET STRING)]

name the following code:

f = File.read("/temp/mib.txt")
name = f.match(/1.3.6.1.2.1.1.5.0/)
puts "device name is #{name}"

It returns the 1.3.6.1.2.1.1.5.0 just like I asked it to, but what I really want is to find the string the contains 1.3.6.1.2.1.1.5.0 and parse out the value myrouter.

Thanks in advance for your help

+1  A: 

You always could use scan:

>> name = f.scan(/1.3.6.1.2.1.1.5.0, value=(\w+)/).flatten.to_s
=> "myrouter"

If you want the ad.local part as well, then instead do:

>> name = f.scan(/1.3.6.1.2.1.1.5.0, value=([\w\.]+)/).flatten.to_s
=> "myrouter.ad.local"
Chris Bunch
Thanks for your help
rahrahruby
Sure, no problem!
Chris Bunch
if the string looks like this [name=1.3.6.1.2.1.1.5.0, value=my-router.ad.local (OCTET STRING) it won't get my-router. I'm sure that its because the regex needs to change to include more than ([\w\.]+)/) could you tell me what I would need to add to get everything between the "value=" and the .ad.local. Thanks
rahrahruby
@rahrahruby Use my idea. ... ([\S]+) ...
HGF
+1  A: 

You must extend your regex to catch the value inside a regex group.

s = File.read("/temp/mib.txt")
m = s.match /\[name=1.3.6.1.2.1.1.5.0, value=([\S]+) \(OCTET STRING\)/
puts "device name is #{m[1]}"
HGF
thanks for the anwser
rahrahruby
Your example is good, but I only want the my-router. yours gives me my-router.ad.local. I tried to modify m = s.match /\[name=1.3.6.1.2.1.1.5.0, value=([\S]+) \(OCTET STRING\)/ to m = s.match /\[name=1.3.6.1.2.1.1.5.0, value=([\S]+) \.ad.local/ but that doesn't work
rahrahruby
You can do with regex also, but I would suggest you to filter the hostname from domain using a second line of code. Just use the example bellow.name = m[1].split('.')[0]
HGF
yeah, I did the split and it worked, but I was hoping to find the regex way. Thanks for all your time and help!
rahrahruby