Home > other >  Convert list of interfaces from show vlan into full name list line by line
Convert list of interfaces from show vlan into full name list line by line

Time:04-19

I need to take list of interfaces from show vlan:

gi1/0/1, gi1/0/2, gi1/0/3, gi1/0/5, gi1/0/7, gi1/0/10
gi1/0/11, gi1/0/13, gi1/0/15, gi1/0/17, gi1/0/19

and get the text output as

interface gi 1/0/1
...
interface gi 1/0/19

I got my original input as a list using following code:

cisco1 ="""gi1/0/1, gi1/0/2, gi1/0/3, gi1/0/5, gi1/0/7, gi1/0/10
gi1/0/11, gi1/0/13, gi1/0/15, gi1/0/17, gi1/0/19
gi1/0/21, gi1/0/31, gi1/0/32, gi1/0/33, gi1/0/34, gi1/0/35, gi1/0/40"""
list1 = cisco1.split()
print(list1)

This gives me a list with extra commas (not every time).

['gi1/0/1,', 'gi1/0/2,', 'gi1/0/3,', 'gi1/0/5,', 'gi1/0/7,', 'gi1/0/10', 'gi1/0/11,', 'gi1/0/13,', 'gi1/0/15,', 'gi1/0/17,', 'gi1/0/19', 'gi1/0/21,', 'gi1/0/31,', 'gi1/0/32,', 'gi1/0/33,', 'gi1/0/34,', 'gi1/0/35,', 'gi1/0/40']

I would like to take each record and remove comma (if its there) and replace "gi" with "int gi" Any help in bash of python would be appreciated.

Update: I came up with this code but i still need to print each int in separate line and add "int " in front of "gi".

CodePudding user response:

You have multiple delimiters in your string.

use regular expression.

import re

cisco1 ="""gi1/0/1, gi1/0/2, gi1/0/3, gi1/0/5, gi1/0/7, gi1/0/10
gi1/0/11, gi1/0/13, gi1/0/15, gi1/0/17, gi1/0/19
gi1/0/21, gi1/0/31, gi1/0/32, gi1/0/33, gi1/0/34, gi1/0/35, gi1/0/40"""

list1 = re.split(r',|\n|", ";', cisco1)

print(list1)

for replacing you can use list comprehension.

finalList = [x.replace("gi","int gi").strip() for x in list1]

print(finalList)

CodePudding user response:

Thank you Pavan. This helped me a lot. Here is final code:

import re
cisco1 ="""gi1/0/1, gi1/0/2, gi1/0/3, gi1/0/5, gi1/0/7, gi1/0/10
gi1/0/11, gi1/0/13, gi1/0/15, gi1/0/17, gi1/0/19
gi1/0/21, gi1/0/31, gi1/0/32, gi1/0/33, gi1/0/34, gi1/0/35, gi1/0/40"""
list11 = re.split(r',|\n|", ";', cisco1)
finalList = [x.replace("gi","int gi").strip() for x in list11]
print(finalList)
for x in finalList:
    print(x)

final lines of output are:

int gi1/0/34
int gi1/0/35
int gi1/0/40

CodePudding user response:

cisco1="gi1/0/1, gi1/0/2, gi1/0/3, gi1/0/5, gi1/0/7, gi1/0/10
gi1/0/11, gi1/0/13, gi1/0/15, gi1/0/17, gi1/0/19
gi1/0/21, gi1/0/31, gi1/0/32, gi1/0/33, gi1/0/34, gi1/0/35, gi1/0/40"

tr -d ',' <<<$cisco1 | tr ' ' '\n'| awk '{ print "interface gi " substr($1,3)}'
# ^remove commas       ^blanks to newlines   

interface gi 1/0/1
interface gi 1/0/2
interface gi 1/0/3
interface gi 1/0/5
interface gi 1/0/7
interface gi 1/0/10
interface gi 1/0/11
interface gi 1/0/13
interface gi 1/0/15
interface gi 1/0/17
interface gi 1/0/19
interface gi 1/0/21
interface gi 1/0/31
interface gi 1/0/32
interface gi 1/0/33
interface gi 1/0/34
interface gi 1/0/35
interface gi 1/0/40
  • Related