所以我有一个数组 ,我需要通过逐行search和接口分割。 我的代码一行一行地循环遍历这个文件。 我想通过“!”分割接口 字符,并将string添加到数组中的元素,以便我可以进一步parsing。
以下是该文件的内容。
! interface Loopback0 description MANAGEMENT ip address 172.xxx.xxx.x ! interface FastEthernet0/0 description m<1> A<LAN on chr-city> no ip address ip flow ingress duplex auto speed auto ! interface FastEthernet0/0.50 description Management encapsulation dot1Q 50 native ip address 172.xxx.xxx.x ! interface FastEthernet0/0.51 description Transit encapsulation dot1Q 51 ip address 172.xxx.xxx.x service-policy input mark ! interface FastEthernet0/1 no ip address shutdown duplex auto speed auto ! interface Serial0/0/0 description m<1> WAN<> V<CL> bandwidth 1536 ip address 172.xxx.xxx.x ip flow ingress no ip mroute-cache service-module t1 timeslots 1-24 no cdp enable service-policy output shape ! router bgp 65052
searchconfiguration存档文件代码
for ($m=0; $m -lt $configFileContents.length; $m++) { $index = 0 if($configFileContents[$m] -eq "interface Loopback0"){ #starting spot $a = @() While($configFileContents[$m] -notmatch "router bgp") { #ending spot if($configFileContents[$m] -ne "!") { #divide the elements $a[$index] += $configFileContents[$m] $m++ } else { $index++ $m++ } } Write-Host "interface archive section" -BackgroundColor Green $a Write-Host "end of interface archive section" }`
问:如何在“!”之间添加所有的接口string 到我的数组中的一个元素和所有下一个到第二个元素,依此类推?
更新的代码
$raw = [IO.File]::ReadAllText("$recentConfigFile") $myArr = @() $raw.Split("!") | % {$myArr += ,$_.Split("`n")} $i = 0 $myArr | % { if ($_[0].Trim() -eq "interface Loopback0") { $start = $i } elseif ($_[0].Trim() -eq "router bgp 65052") { $end = $i } $i++ } $myArr | Select-Object -Skip $start -First ($end-$start)
首先分块
$x = Get-Content -Path 'D:\powershell\Files\input.txt' $x2 = $x -join "`r`n" $x3 = $x2 -split "!`r`n"
简而言之:
$x = @( $(@( Get-Content -Path 'D:\powershell\Files\input.txt' ) -join "`r`n" ) -split "!`r`n" )
然后输出彩色
ForEach ($line in $x) { $local:lineArr = @( $line -split "`r`n" ) $local:arrayInterfaces = @( $local:lineArr | Where-Object {$_ -match '\s*interface\s'} ) $local:arrayNonInterfaces = @( $local:lineArr | Where-Object { $local:arrayInterfaces -notcontains $_ } ) Write-Host -ForegroundColor Red $( $local:arrayInterfaces -join "`r`n" ) Write-Host -ForegroundColor Green $( $local:arrayNonInterfaces -join "`r`n" ) Write-Host ( '#' * 60 ) }
你正在努力的循环和条件。 这应该得到一个数组,每个接口元素作为一个子数组:
$raw = [IO.File]::ReadAllText("C:\Users\Public\Documents\Test\Config.txt") $myArr = @() $raw.Split("!") | % {$myArr += ,$_.Split("`n")}
如果所有你想要的是每个接口部分作为一个string元素,你可以改变最后两行:
$myArr = $raw.Split("!")
之后可能会有一些与数组有关的清理,但是这应该让你有99%的方式。 例如,要获取interface Loopback0和router bgp 65052之间的元素:
$i = 0 $myArr | % { if ($_[0] -like "*interface Loopback0*") { $start = $i } elseif ($_[0] -like "*router bgp 65052*") { $end = $i } $i++ } $myArr | Select-Object -Skip $start -First ($end-$start)