POwershell 将多行合并到数组的一个元素中

问题描述 投票:0回答:1

我有部分交换机配置,包括所有接口以太网端口配置。

Interface Ethernet1/0/12
 switchport mode hybrid
 switchport hybrid allowed vlan 21-29 untag
 switchport hybrid native vlan 21
 mac-authentication-bypass enable
 mac-authentication-bypass guest-vlan 21
Interface Ethernet1/0/13
 switchport mode hybrid
 switchport hybrid allowed vlan 21-29 untag
 switchport hybrid native vlan 21
 mac-authentication-bypass enable
 mac-authentication-bypass guest-vlan 21
Interface Ethernet1/0/14
 switchport mode hybrid
 switchport hybrid allowed vlan 21-29 untag
 switchport hybrid native vlan 21
 mac-authentication-bypass enable
 mac-authentication-bypass guest-vlan 21
Interface Ethernet1/0/15
 switchport mode hybrid
 switchport hybrid allowed vlan 21-29 untag
 switchport hybrid native vlan 21
 mac-authentication-bypass enable
 mac-authentication-bypass guest-vlan 21

我需要像这样转换每个块:

Interface Ethernet1/0/12
 switchport mode hybrid
 switchport hybrid allowed vlan 21-29 untag
 switchport hybrid native vlan 21
 mac-authentication-bypass enable
 mac-authentication-bypass guest-vlan 21

进入数组元素。

“接口Ethernet1/0/12”下方的计数行可能不同

你能举例说明如何做到这一点吗?

arrays string powershell merge combine
1个回答
0
投票

最简单的解决方案是使用

-split
字符串拆分运算符正则表达式,在以非空白字符(
^
)开头的行的开头(
\S
)进行拆分:

$arrayWithBlocksOfLines = 
  (Get-Content -Raw file.txt) -split '(?m)^(?=\S)'
  • 有关正则表达式的说明以及尝试它的选项,请参阅此 regex101.com 页面

  • 上面假设一个文件作为输入;如果要处理的文本位于内存中的变量中,请将

    (Get-Content ...)
    替换为对该变量的引用。

© www.soinside.com 2019 - 2024. All rights reserved.