0

I have a text file similar to this on a remote device:

 D0-23-DB-31-04-3E%20192.168.4.42%20dnat
 68-A8-6D-0C-38-B2%20192.168.4.40%20dnat

I created a small Ruby script to convert this to a string and post it to my Rails application:

 def chilli_list
  hash = File.open("/tmp/client_list", "rb").read
  return hash
 end

The output then looks like:

"D0-23-DB-31-04-3E%20192.168.4.42%20dnat\n68-A8-6D-0C-38-B2%20192.168.4.40%20dnat\n" 

I need to extract the information bit by bit and display in a view. So far, I've not got far. I tried the following which is OK:

str = "D0-23-DB-31-04-3E%20192.168.4.42%20dnat\n68-A8-6D-0C-38-B2%20192.168.4.40%20dpass\n" 

str.each_line do |line|
  puts line.split(" ").first
  puts line.split(" ").second
end

Is that the best way to do it or is there a better way?

Finally and most importantly, I also need to perform a few calculations on the string. I can count the lines with str.lines.count, but what I need is a count of the lines where the third value == nat as in the example above.

How can I go about that?

1
  • 1
    "%20" is a URI escape or "percent escape". It is not a space character. It just represents the encoding of one. Commented Aug 14, 2012 at 19:05

1 Answer 1

2

First, here's how to convert from HTML encoding back into a normal string:

require 'uri'
URI.decode('D0-23-DB-31-04-3E%20192.168.4.42%20dnat') # => "D0-23-DB-31-04-3E 192.168.4.42 dnat"

Here's how to break the entire string into separate decode lines:

"D0-23-DB-31-04-3E%20192.168.4.42%20dnat\n68-A8-6D-0C-38-B2%20192.168.4.40%20dnat\n".split("\n")
  .map{ |l| URI.decode(l) }

which results in this array in IRB:

[
    [0] "D0-23-DB-31-04-3E 192.168.4.42 dnat",
    [1] "68-A8-6D-0C-38-B2 192.168.4.40 dnat"
]

Add on .count{ |l| l[/ dnat$/] } to the end of the previous command and you'll have your count:

"D0-23-DB-31-04-3E%20192.168.4.42%20dnat\n68-A8-6D-0C-38-B2%20192.168.4.40%20dnat\n".split("\n")
  .map{ |l| URI.decode(l) }
  .count{ |l| l[/ dnat$/] }

Which returns 2.

You could also probably simplify the whole process by just directly counting the number of 'nat' occurrences:

"D0-23-DB-31-04-3E%20192.168.4.42%20dnat\n68-A8-6D-0C-38-B2%20192.168.4.40%20dnat\n".scan('nat').count

Which also returns 2.

Sign up to request clarification or add additional context in comments.

1 Comment

coolio, I was miles off clearly! Very interesting, thanks. Was the way I approached getting the individual values out ok (split(' ').first or is there also a better way for that too?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.