pythonbashinterfaceshowvlan

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


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".


Solution

  • 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
    
    
    
    var1="no shut";
    var2="shut"; 
    tr -d ',' <<<$cisco1 | tr ' ' '\n'| awk -v str="$var1" '{ printf "interface gi %s \n", substr($1,3); printf "%s\n", str }'
    
    interface gi 1/0/1
    no shut
    interface gi 1/0/2
    no shut
    
    tr -d ',' <<<$cisco1 | tr ' ' '\n'| awk -v str="$var2" '{ printf "interface gi %s \n", substr($1,3); printf "%s\n", str }'
    
    interface gi 1/0/1
    shut
    interface gi 1/0/2
    shut