3

I am a newbie to parsing.

switch-630624 [standalone: master] (config) # show interface ib status

Interface      Description                                Speed                   Current line rate   Logical port state   Physical port state
---------      -----------                                ---------               -----------------   ------------------   -------------------
Ib 1/1                                                    14.0 Gbps rate          56.0 Gbps           Initialize           LinkUp
Ib 1/2                                                    14.0 Gbps rate          56.0 Gbps           Initialize           LinkUp
Ib 1/3                                                    2.5 Gbps rate only      10.0 Gbps           Down                 Polling

Assume I have an engine which injects the command on the switch, and put the above output as 1 huge string in a variable named "output".

I would like to return a dictionary which includes only the ports number as follows:

{'Ib1/11': '1/11', 'Ib1/10': '1/10', ... , }

I guess I should use the Python`s Subprocess module and regular expressions.

Number of ports can vary (can be 3, 10, 20, 30, 60...).

I will appreciate any kind of direction.

Thanks,

Qwerty

2
  • Why a dictionary? If you only have the ports, then why not use a set or (simpler) a list?
    – cdarke
    Nov 25, 2014 at 14:59
  • I am less concerned with the returned data structure. What I don`t know is how to use regular expressions and string functions to ignore/remove all the irrelevant text (irrelevant header names, irrelevant ---, irrelevant column values etc).
    – Qwerty
    Nov 25, 2014 at 15:01

1 Answer 1

1
# Did this in Python 2.7
import re

# Assume your input is in this file
INPUT_FILE = 'text.txt'

# Regex to only pay attention to lines starting with Ib
# and capture the port info
regex = re.compile(r'^(Ib\s*\S+)')
result = [] # Store results in a list
with open(INPUT_FILE, 'r') as theFile:
  for line in theFile:
    match = regex.search(line)
    if not match: continue
    result.append(match.group())
print result

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.