将 show vlan 中的接口列表逐行转换为全名列表

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

我需要从 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

并将文本输出为

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

我使用以下代码将原始输入作为列表获取:

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)

这给了我一个带有额外逗号的列表(不是每次)。

['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']

我想获取每条记录并删除逗号(如果有)并将“gi”替换为“int gi” python 的 bash 中的任何帮助将不胜感激。

更新: 我想出了这段代码,但我仍然需要在单独的行中打印每个 int 并在“gi”前面添加“int”。

您的字符串中有多个分隔符。

使用正则表达式。

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)

要替换,您可以使用列表理解。

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

print(finalList)
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(,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(,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(,3); printf "%s\n", str }'

interface gi 1/0/1
shut
interface gi 1/0/2
shut

谢谢帕文。这对我帮助很大。 这是最终代码:

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)

最后的输出行是:

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

已删除 - 所有必要的答案都可以在上面找到。 @ufopilot 感谢您的快速回复!